我正在构建一个相册,其中用户有很多相册,每个相册都有很多照片。
专辑类
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。无论出于何种原因,如果用户编辑照片描述或位置,rails 不会更新它们。我相信这与照片是多态的事实有关。
有人可以请帮忙吗?我已经尝试了几个小时并在整个网络上搜索并无法找到解决方案。
谢谢!