可以从一个多态模型的单个记录属于两个(或更多)的模型,在同一时间? [英] Can a single record from a polymorphic model belong to two (or more) models at the same time?

查看:207
本文介绍了可以从一个多态模型的单个记录属于两个(或更多)的模型,在同一时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般新手的问题:如果我有一个名为消息多态模型,并呼吁其他两个型号过滤器用户的has_many:消息,因为在两个... 的关联。可以从信息单条记录属于用户过滤器同时车型?例如,我可以做的:

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

和具有消息#1 在现有用户#1 过滤器#1 ?该 RailsGuides给出了一个非常简短的解释的,所以这方面目前还不清楚我。

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.

推荐答案

当然可以。比方说,一个消息具有所有者(可以是用户或某些其它类)和处理器(即可以是过滤器或某些其他类) 然后在邮件表,你需要列: owner_id,owner_type,processor_id,processor_type 。 而类应该是这个样子:

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

这篇关于可以从一个多态模型的单个记录属于两个(或更多)的模型,在同一时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆