I create a photo album where the user has many albums and each album has many photos.
Album class
Class Album < ActiveRecord::Base
attr_accessible :photos_attributes, :name
has_many photos, :as => imageable
accepts_nested_attributes_for :photos
end
Photo class
Class Photo < ActiveRecord::Base
attr_accessible :description, :location
belongs_to :imageable, :polymorphic => true
end
Album Management Methods
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
Change album form
<%= 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 %>
The problem is that when the edit form is submitted, the photos_attributes data goes through the hash and the rails do not update it properly.
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"}
The identifier sent with the photos_attributes hash is the actual identifier in the photo table in the database. For some reason, rails do not update photo descriptions or locations if the user edits them. I believe that this is due to the fact that photos are polymorphic.
- , , ? .
!