我有一个多态关联如下
class Attachment < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
has_attached_file :file
end
然后在我的用户模型上
class User < ActiveRecord::Base
has_many :attachments, as: :attachable
我希望能够做到以下
attachment = Attachment.create(:file => params[:attachment])
attachment.user = current_user
但我得到了一个
*** NoMethodError Exception: undefined method `user=' for #<Attachment:0x007fee92901ce8>
答案 0 :(得分:2)
attachment
属于attachable
(多态)。设置此方法的正确方法是:
attachment.attachable = current_user
我强烈建议您将关系重命名为以下内容:
class Attachment < ActiveRecord::Base
belongs_to :owner, polymorphic: true
class User < ActiveRecord::Base
has_many :attachments, as: :owner
因为关系的名称owner
比attachable
更明确。亲眼看看:
# What is easier to understan?
attachment.attachable = current_user
# or
attachment.owner = current_user
答案 1 :(得分:0)
你不能以这种方式引用多态关系。它必须是
attachment.attachable = current_user