Can a single record from a polymorphic model belon

2019-05-23 11:10发布

问题:

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))