2011-05-31 92 views
0

對Ruby on Rails 3和ActiveRecord來說,這是一個非常新穎的東西,而且似乎已經在工作中深陷其中。我正在努力處理使用連接從多個表中查詢數據。Rails 3:從關聯表中查詢

很多我見過的例子似乎都基於更簡單的查詢或使用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

基本上,你不需要指定連接:

# 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 
+0

謝謝你,這一直是一個巨大的幫助,我感謝您抽出寶貴時間來回答。 – Andrew 2011-05-31 13:27:10