2015-12-01 68 views
2

我有一个多态关联对我的用户模型轨态关联参考

class User < ActiveRecord::Base 
    has_many :attachments, as: :attachable 

的如下

class Attachment < ActiveRecord::Base 
    belongs_to :attachable, polymorphic: true 
    has_attached_file :file 
end 

然后,我希望能够做到以下几点

attachment = Attachment.create(:file => params[:attachment]) 
attachment.user = current_user 

但我得到一个

*** NoMethodError Exception: undefined method `user=' for #<Attachment:0x007fee92901ce8> 
+0

有什么确切的错误信息?你给的那个不够具体。 –

+0

*** NoMethodError例外:未定义的方法'用户=”为#<附件:0x007fee92901ce8> – Petran

+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 
0

不能引用的多态关系的方式。它不得不是

attachment.attachable = current_user