在 has_many :through 的连接模型上使用named_scopes

发布于 2024-08-31 13:24:41 字数 1041 浏览 5 评论 0原文

我一直在为一些表面上应该很简单的事情而苦苦挣扎。假设我有以下简化模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月下凄凉 2024-09-07 13:24:41

我相信您可以使用

User.find(1).memberships.active.collect(&:group)

,这将返回该用户活跃的所有组。

I believe you can use

User.find(1).memberships.active.collect(&:group)

and this will return all the groups this user is active in.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文