这是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
,但字段不会重新填充。