has_many(不同的对象)为:一类对象
has_many (different objects) as: one type of object
我需要一种将 2 个不同对象引用为 1 个对象的方法。
我有一个需要跟踪收件人的消息对象。问题是收件人可能是用户或联系人。
模型应该是:?
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。
我希望这是有道理的
谢谢
你所做的完全不正确。我认为您需要多对多关联。我的联想是:
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
...我还不能添加评论所以我在这里给出解决方案:当使用 up 的答案接收所有 @message.recipients 每种类型时只有 2 个请求:
RecipientLink.includes(:recipient).where(message_id: @message.id).collect(&:recipient)
我需要一种将 2 个不同对象引用为 1 个对象的方法。
我有一个需要跟踪收件人的消息对象。问题是收件人可能是用户或联系人。
模型应该是:?
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。
我希望这是有道理的 谢谢
你所做的完全不正确。我认为您需要多对多关联。我的联想是:
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
...我还不能添加评论所以我在这里给出解决方案:当使用 up 的答案接收所有 @message.recipients 每种类型时只有 2 个请求:
RecipientLink.includes(:recipient).where(message_id: @message.id).collect(&:recipient)