as an example, i have a model Group and model User
they are connected with :has_many, :through => groups_users
groups_users table has an attribute, called moderator, specifying whether a user is a moderator of the group
question: how do i access all moderators of a given group?
after reading about :with_scope, what comes to mind is
def find_moderators
Group.with_scope(:find=>{:conditions => "moderator=1"})
@moderators=@group.users
end
end
However, after rails 2, with_scope becomes protected, and doesn't allow given code in the controller, so What is the good alternative to that?
solved with
class Group
has_many :groups_users
has_many :moderatorships, :class_name => "GroupsUser",:conditions => {:moderator => true}
has_many :moderators, :through => :moderatorships, :class_name => "User", :source => :user
end
Preferred to Matt van Horn's answer because this one produces only one query when we select user info with @group.moderators, while his solution gives separate query for each moderator
edit: updated to answer Sizzlepants' question. moderators created with this code should have moderator attribute in join model set to true (rails uses :conditions while creating join model), also, if i'd have to code it now, i'd name groups_users memberships for readability.
class User
has_many :group_users
has_many :groups, :through => :groups_users
end
class GroupUser
belongs_to :user
belongs_to :group
named_scope :as_moderator, :conditions => "moderator=1"
end
class Group
has_many :group_users
has_many :groups, :through => :groups_users
def moderators
group_users.as_moderator.map{|gu|gu.user}
end
end
# use it:
@moderators = @group.moderators
or
@all_mods = Group.all.map{|g|g.moderators}.flatten
Monkeypatch!
class Group < ActiveRecord::Base
public :with_scope
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.