在 has_many :through 的连接模型上使用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 named_scope 重复,但这很糟糕。
has_many :active_groups, :through => :memberships, :source => :group, :conditions => ...
所以我的问题:在模型之间直接遍历时有没有办法使用中间命名范围?非常感谢。
I've been beating my head against the wall on something that on the surface should be very simple. Lets say I have the following simplified models:
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
Simple, right? So what I want to do is get a collection of all the groups a user is active in, using the existing named scope on the join model. Something along the lines of User.find(1).groups.active. Obviously this doesn't work.
But as it stands, I need to do something like User.find(1).membrships.active.all(:include => :group)
which returns a collection of memberships plus groups. I don't want that.
I know I can add another has_many on the User model with conditions that duplicate the :active named_scope on the Membership model, but that's gross.
has_many :active_groups, :through => :memberships, :source => :group, :conditions => ...
So my question: is there a way of using intermediary named scopes when traversing directly between models? Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信您可以使用
,这将返回该用户活跃的所有组。
I believe you can use
and this will return all the groups this user is active in.