小编Gle*_*enn的帖子

Activerecord has_many:通过多个模型

我正在尝试访问给定用户的所有评论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)

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

activerecord ruby-on-rails ruby-on-rails-4

8
推荐指数
2
解决办法
3799
查看次数