2013-07-02 89 views
1

祖先寶石,我有一個項目表並用的has_many協會的相關ItemPrices表設置。 ItemPrices表也有一個tier_id字段。用的has_many協會

所以結構基本

Item      ItemPrices 
---------     ------------ 
id      id 
ancestry     item_id 
title      tier_id 
          price 

的項目表被設置爲與has_ancestry和工作正常。

我怎樣才能抓住其中itemprices在某一層級項目分層結構?

+0

你只是試圖找到項目的列表是在給定的範圍tier_id? –

+0

@DanBradbury我想找一個給定的父母的項目列表,其中的孩子在某個層次上有一個itemprice。所以例如我有早餐 - >雞蛋 - >煎雞蛋和早餐 - >雞蛋 - >煮雞蛋。煎雞蛋在一線和二線價格2.Boiled雞蛋只有在層1。所以一個價格,如果我期待在適用於第1級的項目清單,我應該看到早餐 - >雞蛋 - >水煮和煎蛋。如果我在查看適用於第2層的項目列表,那麼我應該只能看到早餐 - >雞蛋 - >煎蛋。所以它試圖通過關聯的tier_id過濾列表。 – robzolkos

回答

1

它必須以某種方式是這樣的:

產品型號:

has_ancestry 
has_many :item_prices 

def self.tree_with_certain_tier(tier_id) 
    scoped.includes(:item_prices).collect{|item| item.item_prices.with_certain_tier(tier_id)}.arrange 
end 

ITEMPRICE型號:

belongs_to :item 
scope :with_certain_tier, lambda {|tier_id| where(:tier_id=>tier_id) } 

,現在你可以抓住你所需要的只是

Item.tree_with_certain_tier(pass_certain_tier_id_here) 

我沒有檢查這一點,但它必須是正確的(或至少點你在正確的方向)

問,如果事情不明確或者你會得到任何錯誤。相信我們會很快解決這些問題

+0

獲取符合範圍的錯誤:item_prices_with_certain_tier,lambda {| tier_id | item_prices.with_certain_tier(tier_id)} 錯誤是未定義的局部變量或方法'item_prices'爲# robzolkos

+0

oopss ...項目模型中的範圍是不必要的...改變了我的答案 – okliv