【问题标题】:Using named_scopes on the join model of a has_many :through在 has_many 的连接模型上使用 named_scopes :through
【发布时间】:2011-02-16 13:22:33
【问题描述】:

我一直在碰壁,表面上应该很简单。假设我有以下简化模型:

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) 的操作,它会返回成员资格和组的集合。我不想那样。

我知道我可以在 User 模型上添加另一个 has_many,其条件与 Membership 模型上的 :active named_scope 重复,但这很糟糕。

has_many :active_groups, :through => :memberships, :source => :group, :conditions => ...

所以我的问题是:在模型之间直接遍历时,有没有办法使用中间命名范围?非常感谢。

【问题讨论】:

    标签: ruby-on-rails join named-scope has-many-through


    【解决方案1】:

    相信你可以使用

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

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

    【讨论】:

    • 类似的东西确实有效,但它非常丑陋:user.memberships.active.all(:include => :group).collect(&:group)
    • 当然……我的错!您需要 collect 部分。真的不是很漂亮……
    • 它也会产生一个数组而不是一个正确的集合。仍然希望对此有更多想法。
    • 它返回一个groups 的数组,不是吗?这是正确的行为
    • 理想情况下,我想要一个可以进一步链接的适当集合,例如 user.memberships.active.groups.find_by_id(23) 或类似的。这似乎是 AR 中的一个空白。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    • 2012-10-02
    • 1970-01-01
    相关资源
    最近更新 更多