2015-12-01 70 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