Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

ruby on rails - Scope with join on :has_many :through association

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 is an extra boolean column within the m2m association table. Given some Users instance current_user, I want to do

current_user.meetings.visible

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

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

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...