0

Model:

class User < ActiveRecord::Base
  attr_accessible :soundcloud_access_token, :soundcloud_expires_at, :soundcloud_refresh_token, :soundcloud_user_id, :soundcloud_username, :photo

  has_one :photo
  accepts_nested_attributes_for :photo

View:

=form_for :user, :url => user_path(@user), :method => :put, :class => 'form-horizontal' do |f|
  %legend Edit Profile
  =f.fields_for :photo do |photo|
    %div.control-group
      =photo.label :image
      %div.controls
        =photo.file_field :image
  =f.submit 'Submit' 

Controller:

  def update
    @user = User.find(params[:id])
    @user.update_attributes(params[:user])
    redirect_to @user
  end

Params:

{"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"nqxi4QKr7g7j0xO41lZqCHvQrGHSd7AXqxEZyskxag8=", "user"=>{"photo"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0xb1d442a0 @original_filename="Dark-Evil-41694.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"user[photo][image]\"; filename=\"Dark-Evil-41694.jpg\"\r\nContent-Type: image/jpeg\r\n", @tempfile=#<File:/tmp/RackMultipart20120908-8454-qgtagx>>}}, "commit"=>"Submit", "action"=>"update", "controller"=>"users", "id"=>"1"}

Error:

Photo(#-646360948) expected, got ActiveSupport::HashWithIndifferentAccess(#76750090)

What the heck am I doing wrong here?

Samo
  • 8,202
  • 13
  • 58
  • 95
  • possible duplicate of [Cannot get this nested form with has_one associatoin to work](http://stackoverflow.com/questions/5576895/cannot-get-this-nested-form-with-has-one-associatoin-to-work) – Samo Sep 08 '12 at 07:37

1 Answers1

2

use

:photo_attributes instead of :photo in attr_accessible

attr_accessible :soundcloud_access_token, :soundcloud_expires_at, :soundcloud_refresh_token, :soundcloud_user_id, :soundcloud_username, :photo_attributes

And this ( this solution by Questioner Samo's himself :) )

:photo_attributes instead of :photo in fields_for

I did not need this step rails 3.2 ,Samo's version from question works great in 3.2

More details in documentation

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#label-Using+with+attr_accessible

Pritesh Jain
  • 9,106
  • 4
  • 37
  • 51
  • That turns out to be only half the issue. I also need to use `:photo_attributes` in the `fields_for` – Samo Sep 09 '12 at 02:14
  • If you want to modify your answer to include the `fields_for :photo_attributes` part of the solution, I'd gladly accept your answer! – Samo Sep 10 '12 at 17:29
  • @Samo, I have updated the answer, I was wondering y so, I use rails 3.2 it works as a charm for me only with `:asscoation` – Pritesh Jain Sep 10 '12 at 18:18