嵌套协会/参与轨道 [英] Nested association/join in rails

查看:90
本文介绍了嵌套协会/参与轨道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,它有一个对象,它有一个所有者具有名称。我想显示的 品牌小号所有者名称在一起。如何做到这一点在一个查询?

I have a seat object that has a car object that has a owner that has a name. I want to display the car brand and the car's owner's name together. How do I do this in one query?

例如:

class Seat < ActiveRecord::Base
  belongs_to :car

  def description
    "I am in a #{car.brand} belonging to #{car.owner.name}"
    # --> how do I replace this with one query?
  end
end

我会注意到,这是一个高度人为的例子,以简化我的问题。我这样做上千次成一排,因此需要更多的效益。

I'll note that this is a highly contrived example to simplify my question. I'm doing this thousands of times in a row, hence the need for more efficiency.

推荐答案

让我们说你是想查询座椅模式,并且要急于负载车和所有者对象,可以使用包括条款。

Let us say you are trying to query the Seat model, and you want to eager load the car and owner objects, you can use the includes clause.

Seat.includes(:car => :owner).where(:color => :red).each do |seat|
  "I am in a #{seat.car.brand} belonging to #{seat.car.owner.name}"
end

这篇关于嵌套协会/参与轨道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆