Rails 3:从关联表进行查询



我对RubyonRails 3和ActiveRecord非常陌生,似乎是在工作的最底层。我很难掌握使用联接从多个表中查询数据的方法。

我看到的很多例子要么似乎是基于更简单的查询,要么使用<rails 3语法。

假设我知道business_unit_group_id并具有以下关联,我将如何查询所有相关Items和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

由于关联已经到位,我不知道是否需要在查询中明确指定任何联接。

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

 # 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

相关内容

  • 没有找到相关文章

最新更新