嵌套关联/加入rails
我有一个seat
对象,其car
对象具有name
的owner
。 我想一起展示car
brand
和car
owner
的name
。 如何在一个查询中执行此操作?
例如:
class Seat how do I replace this with one query? end end
我会注意到这是一个非常人为的例子来简化我的问题。 我连续数千次这样做,因此需要更高的效率。
假设您正在尝试查询Seat
模型,并且您希望加载汽车和所有者对象,则可以使用includes
子句。
Seat.includes(:car => :owner).where(:color => :red).each do |seat| "I am in a #{seat.car.brand} belonging to #{seat.car.owner.name}" end
使用default_scope
class Seat default_scope includes([:car]) end class Car default_scope includes([:owner, :seats]) end
对于我的应用程序中经常使用的多表连接,我在MySQL中创建了一个View。 然后基于视图创建ActiveRecord Rails模型。
根据为视图提供动力的SQL语句,MySQL甚至可以让View进行读/写。 但我只是走简单的路线,并始终将视图视为只读。 您可以将AR模型设置为只读。
通过使用使用视图的Active Record模型,您可以快速单次查询数据库。 而且它们甚至比平时更快,因为MySQL为视图计算一次SQL“计划”,从而更快地使用它。
请记住还检查您的外键是否都已编入索引。 您不希望任何表扫描。