has_many(不同的对象)as:一种对象

时间:2015-08-14 21:48:06

标签: ruby-on-rails polymorphic-associations

我需要一种将2个不同对象引用为1的方法。

我有一个Message对象,需要跟踪收件人。问题是收件人可以是用户还是联系人。

模型应该是:?

class Message < ActiveRecord::Base
  has_many :users, as: :recipients
  has_many :contacts, as: :recipients
end

class User < ActiveRecord::Base
  belongs_to :recipient, polymorphic: true
end

class User < ActiveRecord::Base
  belongs_to :recipient, polymorphic: true
end

因为,我觉得多态关系是以相反的方式构建的。

另外,这种方式不允许我引用我所需要的@ message.recipients。

我希望这是有道理的 谢谢

2 个答案:

答案 0 :(得分:2)

What you have done is completely incorrect. I think you need many-to-many association. My association whould be that:

class Message < ActiveRecord::Base
  has_many :recipient_links
  has_many :users, through: :recipient_links, source: :recipient, source_type: 'User'
  has_many :contacts, through: :recipient_links, source: :recipient, source_type: 'Contact'
end

class Contact < ActiveRecord::Base
  has_many :recipient_links, as: :recipient
  has_many :messages, through: :recipient_links
end

class User < ActiveRecord::Base
  has_many :recipient_links, as: :recipient
  has_many :messages, through: :recipient_links
end

# fields: message_id, recipient_id, recipient_type
class RecipientLink < ActiveRecord::Base
  belongs_to :recipient, polymorphic: true
  belongs_to :message
end

答案 1 :(得分:0)

...我还无法添加评论,所以我在这里给出了解决方案:当使用来自up的答案时,只接收2个请求中的所有@ message.recipients:

RecipientLink.includes(:recipient).where(message_id: @message.id).collect(&:recipient)