加入范围:has_many:通过关联 [英] Scope with join on :has_many :through association

查看:41
本文介绍了加入范围:has_many:通过关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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,我想做

hidden is an extra boolean column within the m2m association table. Given some Users instance current_user, I want to do

current_user.meetings.visible

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

which will retrieve a collection of Meetings for which the user is a participant where the hidden column is false. The closest I have gotten is adding the following scope to the Meetings class

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

scope 确实根据 MeetingParticipations 表过滤了 Meetings,但是没有针对 MeetingParticipations 的加入/条件与current_user相关的code>表.

The scope does filter the Meetings against the MeetingParticipations table, however there is no join/condition against the MeetingParticipations table related to current_user.

问题在于,如果 current_useranother_user 都是某些 Meetings 实例的参与者,则 Meetings> 将为每个将 hidden 设置为 false 的参与者返回结果集中的记录.如果 current_user 为所有 Meetingshidden 设置了 true,如果 another_user 是一个参加任何将 hidden 设置为 false 的相同会议,这些 Meetings 将出现在 Meetings.visible 中结果集.

The issue with this is, if current_user and another_user are both participants for some Meetings instance, a Meetings record in the result set will be returned for each participant that has hidden set to false. If current_user has true set for hidden for all Meetings, if another_user is a participant in any of those same Meetings with hidden set to false, those Meetings will appear in the Meetings.visible result set.

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

Is it possible to have a scope as I've mentioned above which will properly join on the User instance? If not, can someone recommend a solution to this?

推荐答案

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

This is my solution for your problem:

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

这篇关于加入范围:has_many:通过关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆