在has_many的加入模型上使用named_scopes:通过
问题描述:
我一直在表面上碰撞墙上的东西,应该很简单。可以说,我有以下简单的模式:在has_many的加入模型上使用named_scopes:通过
user.rb
has_many :memberships
has_many :groups, :through => :memberships
membership.rb
belongs_to :group
belongs_to :user
STATUS_CODES = {:admin => 1, :member => 2, :invited => 3}
named_scope :active, :conditions => {:status => [[STATUS_CODES[:admin], STATUS_CODES[:member]]}
group.rb
has_many :memberships
has_many :users, :through => :memberships
简单,对吧?所以我想要做的是使用连接模型上的现有命名范围来获取用户活跃的所有组的集合。一些沿着User.find(1).groups.active的行。显然这是行不通的。
但就目前而言,我需要做一些类似于User.find(1).membrships.active.all(:include => :group)
的工作,它会返回会员资格加组的集合。我不想那样。
我知道我可以在用户模型上添加另一个has_many,其条件是在成员模型上重复:active_scope,但这是严重的。
has_many :active_groups, :through => :memberships, :source => :group, :conditions => ...
所以我的问题:是否有一种使用中间命名作用域时直接在模型之间遍历?非常感谢。
答
我相信你可以使用
User.find(1).memberships.active.collect(&:group)
,这将返回所有组该用户是活跃的。
可惜,这是行不通的。 – uberllama 2010-05-06 21:33:50
类似的工作,但它的相当丑陋: user.memberships.active.all(:include =>:group).collect(&:group) – uberllama 2010-05-06 21:43:58
当然...我的错误!你需要“收集”部分。它真的不是很漂亮...... – 2010-05-07 00:20:01