Can a single record from a polymorphic model belong to two (or more) models at the same time?

六眼飞鱼酱① 提交于 2019-12-10 10:46:18

问题


General newbie question: If I have a polymorphic model called Message, and two other models called Filter and User with has_many: messages, as ... association on both. Can a single record from Message belong to User and Filter models at the same time? For example, can I do:

...
User.find(1).messages << Message.find(1)
Filter.find(1).messages << Message.find(1)
...

and have Message#1 available in in User#1 and Filter#1? The RailsGuides gives a very brief explanation, so this aspect is still unclear to me.


回答1:


Yes you can. Let's say a message has owner (that can be User or some other class) and processor (that can be Filter or some other class) Then in the messages table you'll need columns: owner_id, owner_type, processor_id, processor_type. And the classes should look something like:

class Message
  belongs_to :owner, polymorphic: true
  belongs_to :processor, polymorphic: true
end

class User
  has_many :messages
end

class Filter
  has_many :messages
end

However in order to make the message belong to both models you'll need to do something like this:

Message.create(owner: User.find(1), processor: Filter.find(1))
# or like this
User.find(1).messages << Message.create(processor: Filter.find(1))


来源:https://stackoverflow.com/questions/28073289/can-a-single-record-from-a-polymorphic-model-belong-to-two-or-more-models-at-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!