1
這是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
時,我可以看到當new
動作呈現時,create
生成的錯誤也可用,但字段不會重新填充。
謝謝!我一直在掙扎幾個小時。在網絡上發現的所有信息中,沒有一個提到這種細微差別。 – zeromodulus