加入范围:has_many:通过关联

2024-01-15

class Users < ActiveRecord::Base
  has_many :meetings, :through => :meeting_participations
  has_many :meeting_participations
end

class Meetings < ActiveRecord::Base
  has_many :users, :through => :meeting_participations
  has_many :meeting_participations
end

class MeetingParticipations < ActiveRecord::Base
  belongs_to :user
  belongs_to :meeting

  scope :hidden, where(:hidden => true)
  scope :visible, where(:hidden => false)
end

hidden是 m2m 关联表中的额外布尔列。给定一些Users实例current_user, 我想要做

current_user.meetings.visible

这将检索一个集合Meetings用户是其参与者,其中hidden列是false。我得到的最接近的是将以下范围添加到Meetings class

scope :visible, joins(:meeting_participations) & MeetingParticipation.visible

The scope确实过滤了Meetings反对这MeetingParticipations表,但是没有针对该表的连接/条件MeetingParticipations相关表current_user.

这个问题是,如果current_user and another_user都是某些活动的参与者Meetings实例,一个Meetings将为每个参与的参与者返回结果集中的记录hidden set to false. If current_user has true设置为hidden对全部Meetings, if another_user是任何此类会议的参与者hidden set to false, those Meetings将出现在Meetings.visible结果集。

是否有可能有一个像我上面提到的那样的范围,它将正确地加入User实例?如果没有,有人可以推荐一个解决方案吗?


这是我针对您的问题的解决方案:

class User < ActiveRecord::Base
  has_many :meeting_participations
  has_many :meetings, :through => :meeting_participations do
   def visible
     where("meeting_participations.visible = ?", true)
   end
  end
end

@user.meetings.visible

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

加入范围:has_many:通过关联 的相关文章

随机推荐