0

我有以下代碼:Rails的多態嵌套屬性與fields_for無法保存

class User < ActiveRecord::Base 
    has_one :profile_image, :as => :owner, :class_name => 'Image' 
    has_one :cover_image, :as => :owner, :class_name => 'Image' 
end 

和:

class Image < ActiveRecord::Base 
    belongs_to :owner, polymorphic: true 
end 

現在我想建立一個表單,用戶可以更新他/她圖像和他/她的電子郵件。我建立的形式是這樣的:

= form_for @user, :url => pages_upload_path, :html => { :multipart => true } do |form| 
    = form.text_field :email 
    = form.fields_for :profile_image_attributes do |profile_image| 
    = profile_image.file_field :file 
    = form.fields_for :cover_image_attributes do |cover_image| 
    = cover_image.file_field :file 
    = submit_tag("Upload") 

然而,這編譯以下PARAMS哈希:

[2] pry(#<PagesController>)> params[:user] 
=> {"email"=>"[email protected]", 
"profile_image"=> 
    {"file"=> 
    #<ActionDispatch::Http::UploadedFile:0x007f8a41365d30 
    @content_type="image/png", 
    @headers= 
     "Content-Disposition: form-data; name=\"user[profile_image][file]\"; filename=\"Screenshot 2014-04-27 02.57.34.png\"\r\nContent-Type: image/png\r\n", 
    @original_filename="Screenshot 2014-04-27 02.57.34.png", 
    @tempfile= 
     #<File:/var/folders/_2/rgn574910638hqstf85233hh0000gn/T/RackMultipart20140518-88429-15129ld>>}, 
"cover_image"=> 
    {"file"=> 
    #<ActionDispatch::Http::UploadedFile:0x007f8a413653d0 
    @content_type="image/png", 
    @headers= 
     "Content-Disposition: form-data; name=\"user[cover_image][file]\"; filename=\"Screenshot 2014-04-27 02.57.34.png\"\r\nContent-Type: image/png\r\n", 
    @original_filename="Screenshot 2014-04-27 02.57.34.png", 
    @tempfile= 
     #<File:/var/folders/_2/rgn574910638hqstf85233hh0000gn/T/RackMultipart20140518-88429-1oosnc5>>}} 

但是當我保存這個,像這樣,我得到以下錯誤:

@user = User.last 
@user.update_attributes(params.fetch(:user, {}).permit(:email, :profile_image => [:file])) 
# ActiveRecord::AssociationTypeMismatch: Image(#70115863220300) expected, got  
# ActionController::Parameters(#70115879244320) 
# from /Users/kaspergrubbe/.rbenv/versions/2.0.0-p353/lib/ruby/gems/2.0.0/gems 
# /activerecord-4.1.0/lib/active_record/associations/association.rb:216:in 
# `raise_on_type_mismatch!' 

我怎樣才能讓它接受我的屬性profile_image

+0

刪除':class_name =>'Image'可以解決我猜想的問題。 – Pavan

+0

請發佈'控制器代碼'。 – Pavan

回答

3

您需要添加:

accepts_nested_attributes_for :profile_image 
accepts_nested_attributes_for :cover_image 

你得到的錯誤是這樣的導軌的結果分配的屬性。對於每個鍵,它調用#{key}=方法,所以在你的情況下,它試圖將散列分配給profile_image

當你添加accepts_nested_attributes_for很多事情會改變。首先,它將定義profile_image_attributes=方法,該方法預計將用於構建或更新關聯對象的哈希對象。當fields_for注意到此方法已定義時,它將更新字段的名稱以在末尾包含_attributes,因此所有內容都將起作用。

但是請注意,如果沒有關聯對象,fields_for將不會生成,因此您需要在新建和編輯操作中構建這些對象。

+0

哈哈:D爲什麼我沒有看到它。 – Pavan

+0

噢,是的,謝謝你,工作! –