渴望加载多对多关系

时间:2014-07-08 19:25:27

标签: ruby-on-rails ruby-on-rails-4

我有3个型号:

class Thing < ActiveRecord::Base
  has_many :products
  has_many :shops, through: :products
end

class Product < ActiveRecord::Base
  belongs_to :thing
  belongs_to :shop
end

class Shop < ActiveRecord::Base
  has_many :products
  has_many :things, through: :products
end

商店销售很多东西。每个商店都有自己的页面,上面列出了它的东西。产品表有shop_id,thing_id,东西数量和东西价格。 这是控制器:

def show
  @shop = Shop.find(params[:id])
end

并查看:

<% @shop.things.each do |thing| %>
  <%= link_to thing.name, shop_thing_path(id: thing.id, shop_id: @shop.id) %><br>
  <%= thing.products.find_by(shop_id: @shop.id).price %><br>
  <%= thing.products.find_by(shop_id: @shop.id).quantity %>
<% end %>

我无法理解如何急切加载这个权利。现在我得到N * 2个查询(N =事物计数):

SELECT "products".* FROM "products" WHERE "products"."thing_id" = ? AND "products"."shop_id" = 1 LIMIT 1

2 个答案:

答案 0 :(得分:1)

def show @shop = Shop.includes(:things).find(params[:id]) end

以下是与预先加载相关的文档。

http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

答案 1 :(得分:0)

我试图从另一点开始使用@products而不是@ shop.things:

<强>控制器:

def show
  @shop = Shop.find(params[:id])
  @products = @shop.products.includes(:thing).joins(:thing)
end

查看

<% @products.each do |product| %>
  <tr>
    <td><%= link_to product.thing.name, shop_thing_path(id: product.thing_id, shop_id: product.shop_id) %></td>
    <td><%= product.price %></td>
    <td><%= product.quantity %></td>
  </tr>
<% end %>

现在有效。但我仍然无法理解为什么

def show
  @shop = Shop.includes(:things).find(params[:id])
end

不起作用。