参加モデルを使用して、レールにhas_manyの属性:を通じて
-
18-09-2019 - |
質問
例として、私はモデルグループとモデルのユーザーを持っている。
、それらが接続されている:has_manyの、:=> groups_users
スルーgroups_usersテーブルは、ユーザがグループの司会者であるかどうかを指定して、属性と呼ばれるモデレータを有する
質問:?どのように私は与えられたグループのすべてのモデレーターにアクセスします。
について読んだ後:with_scope、何が頭に浮かぶです。
def find_moderators
Group.with_scope(:find=>{:conditions => "moderator=1"})
@moderators=@group.users
end
end
しかし、レール2の後、with_scopeが保護状態になると、コントローラ内のコードを与えることはできませんので、良い選択肢はそれには何ですか?
解決
で解決
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
この1つは唯一のクエリを生成するので、我々は、@のgroup.moderatorsでユーザー情報を選択したときに、彼のソリューションは、各モデレータのために別のクエリを与えながら、マット・ヴァンホーンの答えに好適
編集:Sizzlepants'質問に答えるように更新。私は今それをコーディングする必要があるだろうと、私は読みやすくするためgroups_usersメンバーシップを指定するといいでしょう。
他のヒント
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
モンキーパッチ!
class Group < ActiveRecord::Base
public :with_scope
end
所属していません StackOverflow