2015-12-02 32 views
-1

我无法找出通过关联链接检索多个父母的所有孩子的正确方法。是:grandparent.parents.children关联链接在Rails 4中不正确?

为了简化我有三个型号:

class Customer < ActiveRecord::Base 
    has_many :invoices 
end 

class Invoice < ActiveRecord::Base 
    belongs_to :customer 
    has_many :line_items 
end 

class LineItem < ActiveRecord::Base 
    belongs_to :invoice 
end 

创建几个对象我厌倦了使用从导轨导向的例子后(协会基础:4.3.3.4包括):

Customer.first.invoices.line_items 

它退货:

undefined method `line_items' for #<Customer::ActiveRecord_Associations_CollectionProxy 

是否grandparent.parents.children不可用?

编辑

我没有搜索的grandparent.parents.first.children,但集合中的所有父母的孩子,导轨导游状态:

如果经常检索(@ customer.orders.line_items),

作为一个有效的操作,我想知道这是否是一个错误。

FINAL正如所选答案的评论所述:在ActiveRecord中:范围是可链接的,但关联不是。

回答

1

customer.invoices.line_items无法按照您的方式工作,因为has_many始终链接到单个记录。但你可以实现你使用has_many through 如下想要什么(如果我理解正确的话):

class Customer < ActiveRecord::Base 
    has_many :invoices 
    has_many :line_items, through: :invoices 
end 

class Invoice < ActiveRecord::Base 
    belongs_to :customer 
    has_many :line_items 
end 

class LineItem < ActiveRecord::Base 
    belongs_to :invoice 
end 

,现在你可以这样写:

customer.line_items 

,它会返回所有line_items,其连接到一个客户的发票。

+0

我知道这一点,我感兴趣的是链接协会可用。 – quad

+1

您可以链接范围,但不是关联。所以因为工作范围上的关系,并在单个记录的关联(例如一张发票),你可以写'customer.invoices.active'但不是'customer.invoices.line_items'。 – nathanvda

+0

这就是我正在寻找的。 – quad

0

Customer.first.invoices将返回发票的集合(如数组)。 line_items方法未针对集合进行定义,而是为发票定义。尝试Customer.first.invoices.first.line_items

编辑 - 如果你总是希望要包括的订单行项目,你可以这样做:

class Customer < ActiveRecord::Base 
    has_many :orders, -> { includes :line_items } 
end 

class Order < ActiveRecord::Base 
    belongs_to :customer 
    has_many :line_items 
end 

class LineItem < ActiveRecord::Base 
    belongs_to :order 
end 
+0

这不是我想知道的事儿,检查编辑:)以上 – quad

+0

重读4.3.3.4在轨导向。我相信该页面上的第二个代码片段解释了您正在寻找的行为! :) – user2635088

+0

但是,我该如何“检索订单项”这种方式? – quad

1
Customer.first.invoices.first.line_items 

或者,如果你想所有的数据放在一起,你可以这样做:

results = Customer.first.invoices.includes(:line_items) 

然后,您可以通过循环结果来访问没有DB调用的数据。对于第一个数据例如:results.first.line_items

希望它有帮助!

+0

这不是我想知道的事儿,用'Customer.first.invoices.includes检查上面:) – quad

+0

@quad编辑正如我在答复中提到,你可以将所有数据一起(:line_items)' – Dusht

+0

但是,如何返回所有line_items? – quad