rails多态关联引用

时间:2015-12-01 19:50:08

标签: ruby-on-rails

我有一个多态关联如下

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> 

2 个答案:

答案 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

因为关系的名称ownerattachable更明确。亲眼看看:

# What is easier to understan?
attachment.attachable = current_user
# or 
attachment.owner = current_user

答案 1 :(得分:0)

你不能以这种方式引用多态关系。它必须是

attachment.attachable = current_user