3
我正在建立一个相册,用户有很多专辑,每张专辑都有很多照片。你可以编辑/更新也是嵌套属性的多态模型吗?
相册类
Class Album < ActiveRecord::Base
attr_accessible :photos_attributes, :name
has_many photos, :as => imageable
accepts_nested_attributes_for :photos
end
照片类
Class Photo < ActiveRecord::Base
attr_accessible :description, :location
belongs_to :imageable, :polymorphic => true
end
相册控制器方法
def create
@album = current_user.albums.build(params[:album])
if @album.save
redirect_to @album, :notice => "Successfully created album."
else
render :action => 'new'
end
end
def edit
@album = Album.find(params[:id])
end
def update
@album = Album.find(params[:id])
if @album.update_attributes(params[:album])
redirect_to @album, :notice => "Successfully updated album."
else
render :action => 'edit'
end
end
编辑相册表格
<%= form_for @album do |f| %>
<%= f.label :album_name %><br />
<%= f.text_field :name %>
<%= f.fields_for :photos do |photo| %>
<%= photo.label :photo_description %>
<%= photo.text_field :description %>
<%= photo.label :photo_location %>
<%= photo.text_field :location %>
<% end %>
<% end %>
问题是,当编辑表单提交时,photos_attributes作为散列来通过,并且rails没有正确更新它。
Parameters: { "album"=>{"user_id"=>"1", "name"=>"Lake Tahoe",
"photos_attributes"=>{"1"=>{"description"=>"Top of the Mountain!", "id"=>"2"},
"2"=>{"description"=>"From the cabin", "id"=>"5"}}},
"commit"=>"Update Ablum", "id"=>"10"}
与photos_attributes哈希一起发送的ID是在数据库中的照片表中的实际ID。无论出于何种原因,如果用户编辑它们,则导航栏不会更新照片说明或位置。我相信这与照片是多态的事实有关。
有人请请请帮忙?我一直在尝试几个小时,并在网络上搜索,一直未能找到解决方案。
谢谢!
你可以在你的问题中添加控制器的创建/更新方法吗? – lesce
刚刚添加了相册控制器方法。他们虽然没有特别特别的。创建工作正常,照片创建与他们的描述和位置。奇怪的是,如果我编辑一张专辑并删除一张照片,它就可以正常工作。唯一的问题是更新照片的模型属性(描述和位置)。我有另一个模型是一个嵌套的属性,并更新它的工作正常。所以我非常肯定这与这样一个事实有关,即照片是多态的,并且正在抛弃东西。 –
编辑相册时请检查导轨服务器输出。 – lesce