验证失败时如何重新填充表单字段?

时间:2013-07-02 01:03:18

标签: ruby-on-rails ruby ruby-on-rails-3.2

这是erb模板:

<div id='recipe-form'>
  <% if @recipe.errors %>
    <div id='errors'>
      <% @recipe.errors.messages.each do |field, messages| %>
        <div class='error'>
          <div class=field'><%= field %></div>
          <div class='messages'>
            <ul>
            <% messages.each do |message| %>
              <li><%= message %></li>
            <% end %>
            </ul>
          </div>
        </div>
      <% end %>
    </div>
  <% end %>
  <%= form_for @recipe, :html => {:multipart => true}, :url => '/recipes'  do |f| %>

    <%= f.label :title, 'title' %>
    <%= f.text_field :title %>

    <div id="photo-upload">
      <%= file_field :photo0, :image, :id => 0 %>
    </div>

    <div id='existing-photos'>
      <% recipe.photos.each do |photo| %>
        <div id='<%= photo.id %>'>
          <img src='<%= photo.image.url(:thumb) %>' />
          <ul>
            <li>
              <%= link_to 'delete',
                    recipe_photo_url(
                      :recipe_id => @recipe.slug,
                      :id => photo.id
                    ),
                    :method => :delete,
                    :remote => true
              %>
            </li>
          </ul>
        </div>
      <% end %>
    </div>

    <%= f.label :body, 'body' %>
    <%= f.cktext_area :body, :ckeditor => {:width => "500"} %>

    <%= f.label :tags, 'tags (comma separated)' %>
    <%= text_field_tag :tags %>

    <%= submit_tag 'submit' %>
  <% end %>
</div>

这是创建动作:

def create
  @recipe = Recipe.new(params[:recipe])

  photo_keys = params.keys.select{|k|k.match(/^photo/)}
  @photos = []
  photo_keys.each do |photo_key|
    @photos << Photo.new(params[photo_key])
  end

  @recipe.tags = Tag.parse(params[:tags])

  @recipe.author = current_user

  if @recipe.save &&
       @photos.all?{|photo|photo.save}
    @photos.each do |photo|
      photo.recipe_id = @recipe.id
      photo.save
    end
    flash[:notice] = 'Recipe was successfully created.'
    redirect_to recipe_url(@recipe.slug)
  else
    flash[:error] = 'Could not create recipe. '
    flash[:error] += 'Please correct any mistakes below.'
    render :action => :new
  end
end

这是新动作:

def new
  @recipe = Recipe.new
end

我读到如果我在上面使用form_for,那么这些字段将自动重新填充。

当我从erb模板中检查@recipe.errors时,我可以看到create生成的错误在呈现new操作时也可用,但字段不会重新显示-populate。

1 个答案:

答案 0 :(得分:1)

我实际上不确定render action:的作用,但我的工作和工作是:不使用render :new渲染动作而是渲染模板。

您需要设置相同的实例变量(带有@的变量),这些变量已存在于您的创建操作中。