Rails 3:从关联表中查询

时间:2011-05-31 12:11:39

标签: ruby-on-rails ruby-on-rails-3 activerecord

我是Ruby on Rails 3和ActiveRecord的新手,似乎已经被深深地投入到工作中。我正在努力解决使用连接从多个表中查询数据的问题。

我见过的很多例子似乎都是基于更简单的查询或使用< rails 3语法。

鉴于我知道business_unit_group_id并具有以下关联,我如何查询所有相关项目和ItemSellingPrices的列表?

class BusinessUnitGroup < ActiveRecord::Base
  has_many :business_unit_group_items
end

class BusinessUnitGroupItem < ActiveRecord::Base
  belongs_to :business_unit_group
  belongs_to :item
  belongs_to :item_selling_price
end

class Item < ActiveRecord::Base
  has_many :business_unit_group_items
end

class ItemSellingPrice < ActiveRecord::Base
  has_many :business_unit_group_items
end

我很困惑我是否需要明确指定查询中的任何连接,因为关联已到位。

1 个答案:

答案 0 :(得分:1)

基本上,您不需要指定连接:

 # This gives you all the BusinessUnitGroupItems for that BusinessUnitGroup
 BusinessUnitGroup.find(id).business_unit_group_items

 # BusinessUnitGroupItem seems to be a rich join table so you might
 # be iterested in the items directly:
 class BusinessUnitGroup < ActiveRecord::Base
   has_many :items through => :business_unit_group_items
   # and/or
   has_many :item_selling_prices, through => :business_unit_group_items
   ...
 end
 # Then this gives you the items and prices for that BusinessUnitGroup:
 BusinessUnitGroup.find(id).items
 BusinessUnitGroup.find(id).item_selling_prices

 # If you want to iterate over all items and their prices within one 
 # BusinessUnitGroup, try this:
 group = BusinessUnitGroup.include(
   :business_unit_group_item => [:items, :item_selling_prices]
 ).find(id)
 # which preloads the items and item prices so while iterating,
 # no more database queries occur