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,这些字段将自动重新填充。

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

4

1 回答 1

2

我实际上不确定做什么render action:,但我所做和工作的是:而不是渲染动作,只是使用render :new.

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

于 2013-07-02T01:06:37.763 回答