0

控制器: posts_controller.rb

def post_creator
    @post = Post.new
end

def create
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render action: 'show', status: :created, location: @post }
      else
        format.html { render template: 'posts/post_creator' }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
end

模型: post.rb

class Post < ActiveRecord::Base
  validates :content, :presence => true
end

浏览量: post_creator.html.erb

<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.select(:name, options_for_select([['Default', 'Default'],['Test', 'Test']]),{:include_blank => 'Select Post Type'}) %>
  </div>
  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

问题:当表单被提交并且用户从选择标签中选择一个名称为“默认”并且未能填写内容时,验证失败并且当它呈现 post_creator.html.erb 但之前已经选择的名称时未填写,它选择选择帖子类型。我不知道这正在发生。

任何帮助将不胜感激。

谢谢

4

1 回答 1

1

试试这个

<%= f.select(:name, options_for_select([['Default', 'Default'],['Test', 'Test']], :selected => params[:post][:name]),{:include_blank => 'Select Post Type'}) %>
于 2013-10-25T05:58:18.393 回答