祖先宝石与has_many协会

时间:2013-07-02 11:13:54

标签: ruby-on-rails ancestry

我有一个Items表和一个带有has_many关联的关联ItemPrices表设置。 ItemPrices表还有一个tier_id字段。

所以结构基本上是

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

Items表的设置与has_ancestry一样,并且工作正常。

如何获取itemprices在特定层中的项目层次结构?

1 个答案:

答案 0 :(得分: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)

我没有检查这个但是它必须是正确的(或者至少指向正确的方向)

询问是否有不清楚的地方或您会收到任何错误。我们一定会尽快修复它们

相关问题