我有以下代码:
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")
然而,编译为以下参数哈希:
[2] pry(#<PagesController>)> params[:user]
=> {"email"=>"kasper@example.com",
"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 :(得分:3)
您需要添加:
accepts_nested_attributes_for :profile_image
accepts_nested_attributes_for :cover_image
您获得的错误是rails分配属性的方式的结果。对于每个键,它调用#{key}=
方法,因此在您的情况下,它会尝试将哈希值分配给profile_image
。
当您添加accepts_nested_attributes_for
时,很多事情都会发生变化。首先,它将定义profile_image_attributes=
方法,该方法需要Hash对象,该对象将用于构建或更新关联对象。当fields_for
注意到此方法已定义时,它会更新字段的名称以在结尾处包含_attributes
,因此一切都会有效。
但请注意,如果没有关联对象,则不会构建fields_for,因此您需要在新的和编辑操作中构建这些对象。