是:grandpatent.parents.children关联链接在Rails4中不正确



我很难找到通过关联链检索多个父级的所有子级的正确方法。

为了简化,我有三个模型:

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

祖父母.祖父母.孩子不能用吗?

编辑

我不是在搜索祖父母.parents.first.children,而是在集合中所有父母的所有孩子,rails guides state:

如果您经常直接从客户处检索行项目(@customer.orders.line_items),

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

FINAL如所选答案的注释所述:在ActiveRecord中:作用域是可链接的,但关联不是。

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

并且它将返回连接到客户的发票的所有CCD_ 4。

Customer.first.invoices.first.line_items

或者,如果你想把所有的数据放在一起,你可以做一些类似的事情:

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

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

希望它能有所帮助!

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

最新更新