Activerecord has_many:通过多个模型

Gle*_*enn 8 activerecord ruby-on-rails ruby-on-rails-4

我正在尝试访问给定用户的所有评论user.comments.查询将通过两个不同的模型,这两个模型可能都返回结果.我的关系如下:

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
Run Code Online (Sandbox Code Playgroud)

评论被验证属于参与者或组织者.

我不知道该如何解决这个问题.我试过了

has_many :comments, through: :participants
has_many :comments, through: :organisers
Run Code Online (Sandbox Code Playgroud)

has_many :comments, through: [:organisers, :participants]
Run Code Online (Sandbox Code Playgroud)

但最后一个不是铁轨.有没有正确的方法来做到这一点?谢谢!

mag*_*ni- 10

has_many :comments, ->(user) {
  unscope(where: :user_id).
  left_joins(:organizer, :participant).
  where('organizers.user_id = ? OR participants.user_id = ?', user.id, user.id)
}
Run Code Online (Sandbox Code Playgroud)

unscope用于删除子句comments.user_id = ?(定义关系时默认添加的子句has_many)。被left_joins称为 on Comment,因此您需要传入 on 上定义的关系名称Comment,因此本例中使用单数。


小智 -1

我相信您的关联会感到困惑,因为 user.comments 不知道它是通过参与者还是组织者,因此最好的选择是声明两个不同的连接(具有不同的名称):

http://guides.rubyonrails.org/association_basics.html#self-joins