我有一个用于创建模型(名为 Image)的表单以及该模型在同一视图上的所有实体的列表。该模型与称为 Deck 的第二个模型以一对多的关系关联(一个 Deck 有许多图像)。我认为的列表如下所示:
# image list
<% @deck.images.each do |img| %> # iterates also through invalidated model
<%= link_to 'Delete', deck_image_path(@deck, img),
:confirm => 'Sure?', :method => :delete %>
<% end %>
当@image 对象的验证失败时,就会出现我的问题。迭代还遍历无效的图像对象,并为下一行给出错误,说明该对象没有这样的路径。
我可以检查每个对象的 .new_record?,但这是首选方式吗?还是我做错了什么?我没有其他人遇到过这样的问题;/
更新 1 - 控制器
def create
@deck = Deck.find(params[:id])
@image = @deck.images.build(params[:image])
respond_to do |format|
if @image.save
# redirect
flash[:notice] = "Saved succesfully."
format.html { redirect_to(@deck) }
else
# render
format.html {
flash.now[:error] = "Could not be saved."
render 'decks/show'
}
end
end
end
更新 2 - 更多混乱
好吧,好吧,我现在完全糊涂了。将 create 方法中的第二行从
# not working
@image = @deck.images.build(params[:image])
至
# working
@image = Image.new(params[:image])
@image.deck = @deck
似乎工作没有任何错误。有什么区别?
更新 3 - 查看和错误消息
<h3>Upload Image</h3>
<%= form_for @image, :url => deck_images_path(@deck), :html => { :multipart => true } do |form| %>
<fieldset>
<legend>Upload new image</legend>
<%= render :partial => 'shared/model_errors', :locals => {:model => @image} %>
<%= form.file_field :image %><br/>
<%= form.submit "Upload", :class => 'btn btn-primary' %>
</fieldset>
<% end %>
<h3>Show all existing images</h3>
<% @deck.images.each do |img| %>
<%= image_tag img.image.url %>
<%= link_to 'Delete'.html_safe, deck_image_path(@deck, img) %>
<% end %>
错误信息:
No route matches {:controller=>"images", :action=>"destroy", :deck_id=>#<Deck id: 1,
name: "Test", description: "Test", created_at: "2012-12-10 20:44:22",
updated_at: "2012-12-10 20:44:22">, :id=>#<Image id: nil, created_at: nil,
updated_at: nil, image_file_name: nil, image_content_type: nil,
image_file_size: nil, image_updated_at: nil, deck_id: 1>}