簡體   English   中英

在rails has_many中使用join模型屬性:through

[英]using join model attributes in rails has_many :through

例如,我有一個模型組和一個模型用戶

它們與:has_many,:through => groups_users連接

groups_users表具有稱為主持人的屬性,用於指定用戶是否為該組的主持人

問題:如何訪問給定組的所有主持人?

閱讀有關:with_scope的內容后,我想到的是

def find_moderators
 Group.with_scope(:find=>{:conditions => "moderator=1"})
   @moderators=@group.users
 end
end

但是,在rails 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

首選馬特·范·霍恩(Matt van Horn)的答案,因為當我們使用@ group.moderators選擇用戶信息時,此查詢僅產生一個查詢,而他的解決方案為每個主持人提供單獨的查詢

編輯:已更新,可以回答Sizzlepants的問題。 使用此代碼創建的主持人應將聯接模型中的moderator屬性設置為true(在創建聯接模型時rails使用:conditions),此外,如果我現在必須對其進行編碼,則我將命名為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM