2012-01-10 221 views
0

首先,如果标题不是非常准确,请原谅。如何使用ActiveRecord通过另一个集合访问集合

比方说,我有这些模型:

class User < ActiveRecord::Base 
    belongs_to :user_group 
end 

class UserGroup < ActiveRecord::Base 
    has_many :users 
    has_many :records 
end 

class Record < ActiveRecord::Base 
    belongs_to :user_group 
    has_many :invoices 
end 

class Invoice < ActiveRecord::Base 
    belongs_to :record 
end 

我想从CURRENT_USER(用户)对他的用户组的所有未付发票来访问。类似这样的:

current_user.user_group.records.invoices.where(:payment => false) 

显然上面的代码不起作用。我发现的最接近的做法是这样的:

class UserGroup 
    def unpaid_invoices 
    records.map{|r| r.invoices.unpaid} 
    end 
end 

class Invoice 
    def self.unpaid 
    where(:payment => false) 
    end 
end 

,然后我可以这样做:

current_user.user_group.unpaid_invoices 

然而,这是不可伸缩的,因为当我想用一个新的条件,如与发票金额大于1000美元,我需要在这些模型中创建两个新方法。

有一些魔术导轨的方式来做到这一点?我错过了什么吗?谢谢!

+2

你可以声明里面'UserGroup'像'的has_many:发票:通过=>:records' – taro 2012-01-10 20:32:35

+0

禾,这是如此简单而有用的。我现在觉得很高兴:)。请将它作为答案发布,我会接受它。谢谢。 – 2012-01-10 21:33:01

+0

顺便说一句,你的解决方案令我感到惊讶,因为直到现在,我一直只使用'has_many:through'来实现多对多的关系。 我刚看到这个方法也被记录在了Rails指南: _The的has_many:通过关联是通过嵌套的has_many associations._ 设置“快捷方式”,也有用http://guides.rubyonrails.org/association_basics .html#the-has_many-through-association – 2012-01-10 22:21:29

回答

0

您可以添加类似的东西到用户组:

has_many :invoices, :through => :records 
相关问题