views:

11

answers:

1

Hi guys

I am trying I have a simple one-to-many association. I am trying to update photos that belong to an album through a nested form:

The edit form for the photo album:

<%= semantic_form_for(@album, :url => user_album_path(@user, @album), :html => {:method => :put} ) do |f| %>

<%= f.inputs do %> <%= f.input :title %> <%= f.input :description %> <% end %> <%= f.inputs :for => :photos do |builder|%> <%= builder.input :_destroy, :as => :boolean %> <% end %> <%= f.submit "Submit", :disabled_with => 'Submiting...' %> <% end %>

It works and doesnt work at the same time. Obviously there is no problem with the title and description, and formtastic correctly makes a checkbox for every photo in the album. But here I already have my first question:

1) How can I display the photo next to the checkbox? I managed to solve that myself:

<%= image_tag(builder.object.image.url(:album)) %>

Displayes the image.

Here the album and album model:

class Album < ActiveRecord::Base

  belongs_to          :user
  has_many            :photos, :dependent => :destroy

  #attr_accessible     :title, :description 

  validates_presence_of :title, :description

  accepts_nested_attributes_for :photos, :allow_destroy => true
end

And the photo model:

class Photo < ActiveRecord::Base
  belongs_to        :user
  belongs_to        :album

  has_attached_file :image, :styles => { :original => ["441x800>", :png], 
                                         :album => ["140x140#", :png], 
                                         :tiny => ["16x16#", :png] }

  validates_attachment_presence :image
  validates_attachment_content_type :image, :content_type => ["image/jpeg", "image/png", "image/gif"]
 end

The album controller:

def update
    @user = User.find(params[:user_id])
    @album = @user.albums.find(params[:id])
    if @album.update_attributes(params[:album][:photos_attributes])
      flash[:success] = t('users.flash.album_updated')
      redirect_to @user
    else
      render :edit
    end
end

The error thrown out:

ActiveRecord::UnknownAttributeError in AlbumsController#update

unknown attribute: 0
Rails.root: /Users/stefanohug/orangerie

Application Trace | Framework Trace | Full Trace
app/controllers/albums_controller.rb:50:in `update'
Request

Parameters:

{"_snowman"=>"☃",
 "_method"=>"put",
 "authenticity_token"=>"bE4AidmbaVoG9XBqolCxheyWtd7qeltkIpMRgd8c4Fw=",
 "album"=>{"title"=>"lol",
 "description"=>"hihi",
 "photos_attributes"=>{"0"=>{"_destroy"=>"1",
 "id"=>"72"},
 "1"=>{"_destroy"=>"1",
 "id"=>"73"},

Line 50 corresponds to the update_attributes line.

Thanks for your help people.

Stef

A: 

I have found the error. It was in the controller:

@album.update_attributes(params[:album][:photos_attributes])

should read:

@album.update_attributes(params[:album])

Duh... :D

Stefano