2012-05-03 29 views
2

我試圖創建一個簡單的rails 3.2應用程序。圖片(#70365286921100)預計,得到陣列(#70365535770260)錯誤

爲了簡單起見,應用程序有兩種型號:產品和圖像

產品應該有很多圖片,所以這裏是我的模型:

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 

我使用active_admin和這裏我的形式創造一個產品:

<%= 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 %> 

當我提交表單,我得到以下異常:

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"} 

爲什麼會發生?任何人都可以請幫我嗎?

在此先感謝!

回答

1

我相信你的產品型號需要accepts_nested_attributes_for :images。該產品型號應該是這樣的:

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

如果你看看你的PARAMS哈希,你看:

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

做什麼accepts_nested_attributes_for是改變你則params的結構以適應一對一許多關係由has_many :images關聯指定。

假如你在形式不止一個形象,你的PARAMS哈希將包含:

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

此外,還要確保你調用@product.images.build到達視圖之前的某個地方,如果@product是新的。