Activerecord has_many:通过多个模型 [英] Activerecord has_many :through through multiple models
问题描述
我正在尝试使用 user.comments
访问给定用户的所有评论。该查询将通过两个不同的模型,这两个模型都可能返回结果。我的关系设置如下:
I'm trying to access all comments from a given user with user.comments
. The query is to go through two different models, which likely both return results. My relations are set up as follow:
class User < ActiveRecord::Base
has_many :organisers
has_many :participants
has_many :comments, through: :participants / :organisers (see explenation below)
end
class Organiser < ActiveRecord::Base
belongs_to :user
end
class Participant < ActiveRecord::Base
belongs_to :user
end
class Comment < ActiveRecord::Base
belongs_to :organiser
belongs_to :participant
end
已确认评论属于参与者或组织者。
A comment is validated to belong to either a participant, or an organiser.
我不确定该如何处理。我已经尝试过
I'm not sure how to go about this. I've tried
has_many :comments, through: :participants
has_many :comments, through: :organisers
和
has_many :comments, through: [:organisers, :participants]
但是最后一个是吨轨。有适当的方法来做到这一点吗?谢谢!
But that last one isn't rails. Is there a proper way to do this? Thanks!
推荐答案
您能做些简单的事情吗:
Could you do something as simple as:
has_many :comments, -> { joins(:participant, :organizer) }, class_name: 'Comment'
此 返回所有具有参与者或组织者用户的评论,因为Rails倾向于默认 joins
为内部联接。您甚至可能不需要:class_name
自变量。
This should return all comments that have a Participant or Organizer User, since Rails tends to default joins
to an inner join. You may not even need that :class_name
argument.
这篇关于Activerecord has_many:通过多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!