验证失败时,选择不预先填充的框

时间:2013-10-25 05:06:14

标签: ruby-on-rails ruby-on-rails-3

控制器: 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 %>

问题:提交表单并且用户从select标记中选择名称为“Default”并且无法填写内容时,验证将失败,并在呈现post_creator.html时.erb但未填充之前已选择的名称,它会选择“选择帖子类型”。我不知道Y这是发生了什么。

任何帮助都将非常感激。

由于

1 个答案:

答案 0 :(得分:1)

试试这个

<%= f.select(:name, options_for_select([['Default', 'Default'],['Test', 'Test']], :selected => params[:post][:name]),{:include_blank => 'Select Post Type'}) %>