0

When I try to submit a simple nested form Rails give me an error:

NoMethodError in UserController#update
undefined method `[]' for #<ActionDispatch::Http::UploadedFile:0x3f4e318>

And params are:

{
 "utf8"=>"✓",
 "authenticity_token"=>"HFWawKp4RH7+AFV0yQ1cXpzxHDfubKTKkiDiS6QKnJk=",
 "user"=> { 
  "name"=>"Alex",
  "pics_attributes"=> { 
    "pic"=>#<ActionDispatch::Http::UploadedFile:0x3f4e318
    @original_filename="Beautiful Sky_thumb.jpg",
    @content_type="image/jpeg",
    @headers="Content-Disposition: form-data; name=\"user[pics_attributes][pic]\"; filename=\"Beautiful Sky_thumb.jpg\"\r\nContent-Type: image/jpeg\r\n",
    @tempfile=#<File:C:/Users/Alex/AppData/Local/Temp/RackMultipart20120824-4784-5rmxid>>
  }
 },
"commit"=>"Save User"
}

UserController#update

def update
 @user = User.new(params[:user])
 @user.save
end

Form (It uses generic form builder. Maybe that causes an error?)

<%= form_for :user, url: '/user/update', html: {multipart: true} do |user| %>
  <%= user.hidden_field :name, {value: 'Alex'} %>
  <%= user.fields_for :pics_attributes do |pic| %>
    <%= pic.file_field :pic %>
  <% end %>
  <%= user.submit %>
<% end %>

User model

class User < ActiveRecord::Base
  attr_accessible :name, :pics_attributes
  has_many :pics
  accepts_nested_attributes_for :pics
end

Pics model

class Pics < ActiveRecord::Base
  belongs_to :user
  attr_accessible :image
  mount_uploader :image, PicUploader
end

Where to dig for an error?

The code above is for Carrierwave, but I tried to switch to Paperclip and errors were the same.

1 Answers1

1

You said you solved it, but I think you were doing it wrong in the first place.

You should pass the same value you used in nested_atributes_for for fields_for. Therefore user.fields_for :pics_attributes should be user.fields_for :pics.

vise
  • 12,713
  • 11
  • 52
  • 64
  • I tried your solution, but if I only replace `:pics_attributes` to `:pics` - it gives me a _"can't mass-assign error"_. Furthermore, if I replace `:pics_attributes` to `:pics` at attr_accessible - it says _"Pic expected, got Array"_ – Alex Norton Aug 27 '12 at 10:05
  • 1
    I found nested forms to be beastly. That said, `fields_for :pics` will work if you have `attr_accessible :pics_attributes` and your relationships are correctly setup. If nothing shows up in your form, it's because there are no associated pics. You'll need to build a new one in the controller. – agmin Oct 17 '12 at 20:00