Evgeny Bragin
Evgeny Bragin

Reputation: 21

Image(#70365286921100) expected, got Array(#70365535770260) error

I'm trying to create a simple rails 3.2 app.

To keep it simple, the app has two models: Product and Image

The Product should have many Images, so here are my models:

class Product < ActiveRecord::Base
  has_many :images, :class_name => 'Image'
end

class Image < ActiveRecord::Base
  belongs_to :product
  has_attached_file :image, :styles => { :normal => "300x300", :small => "70x70" }
end

I'm using active_admin and here is my form to create a product:

  <%= semantic_form_for [:admin, @product], :html => {:multipart => true} do |f| %>

    <%= f.inputs :title, :description, :price %>

    <%= f.semantic_fields_for :images do |f2| %>
        <%= f2.file_field :image %>
    <% end %>

    <%= f.buttons :commit %>
  <% end %>

When I submit the form, I get the following exception:

Image(#70365286921100) expected, got Array(#70365535770260)

{"utf8"=>"✓",
 "authenticity_token"=>"waFPhUIJPD90r5SRVmvvYBEcpZHgFJbM325wZDknWf8=",
 "product"=>{"title"=>"rfrfrf",
 "description"=>"rfrfr",
 "price"=>"200.99",
 "images"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007ffe63d19e58 @original_filename="IMG_0097.JPG",
 @content_type="image/jpeg",
 @headers="Content-Disposition: form-data; name=\"product[images][image]\"; filename=\"IMG_0097.JPG\"\r\nContent-Type: image/jpeg\r\n",
 @tempfile=#<File:/var/folders/_j/s1n6_4551cxc765p1zm8w54r0000gq/T/RackMultipart20120503-2609-bwvbis>>}},
 "commit"=>"Create Product"}

Why is it happening? Can anyone please help me out?

Thanks in advance!

Upvotes: 2

Views: 3310

Answers (1)

xfactorial
xfactorial

Reputation: 161

I believe you need accepts_nested_attributes_for :images in your Product model. The Product model should look like:

class Product < ActiveRecord::Base
  has_many :images, :class_name => 'Image'
  accepts_nested_attributes_for :images
end

If you look at your params hash, you see:

"images"=>{"image"=> ...

What accepts_nested_attributes_for does is to change the structure of your params to accommodate the one-to-many relationship specified by the has_many :images association.

Supposing you have more than one image in the form, your params hash would contain:

"images_attributes"=>{"0"=>{"image"=> ...  }, "1"=>{"image" => ... }, ...}

Also, make sure you call @product.images.build somewhere before you reach the view if the @product is new.

Upvotes: 2

Related Questions