2014-07-17 53 views
0

我已經編寫了一個範圍來過濾掉'free entry = true'結果。我希望範圍適用於產品數據庫及其子產品job_product。基於父模型篩選子模型布爾值

Product.rb

# id    :integer   not null, primary key 
# title   :string(255) 
    ............ 
# free_entry  :boolean   default(FALSE) 

class Product < ActiveRecord::Base 

    scope :not_free_entry_scope, -> { where(free_entry: false) } 
    has_many :job_products, dependent: :destroy, 
        inverse_of: :product 

job_product.rb

# Table name: job_products 
# 
# id   :integer   not null, primary key 
# job_id  :integer 
# product_id :integer 
# quantity  :integer   default(1) 
# frozen_cache :text 
# created_at :datetime 
# updated_at :datetime 
# 

class JobProduct < ActiveRecord::Base 

    # associations 
    belongs_to :product, inverse_of: :job_products 
    scope :not_free_entry_scope, -> { where(free_entry: false) } 

我知道它,我可以範圍它像這樣的軌道控制檯,

Product.where("free_entry = true") 

我能範圍產品模型成功,但是當我嘗試將相同的範圍應用於job_product模型,並在控制器中使用它時,它會吐出一個n錯誤

Unknown column 'job_products.free_entry' in 'where clause' 

如何將範圍限定爲父類的子級。

感謝

回答

3

你的錯誤是因爲您使用的是Object.property作爲哈希的關鍵,這不是有效的語法。你需要做的是告訴它加入產品表,然後你可以用merge重新使用產品的範圍。

試試這個:

class JobProduct 
    ... 
    scope :not_free, -> { joins(:product).merge(Product.not_free_entry_scope) } 
    ... 
end 
+0

感謝@NickVeys,這是有道理的,但我留下了錯誤 協會命名爲「產品」是不是JobProduct發現;也許你拼錯了嗎? –

+0

所以我把它改爲 範圍:not_free, - > {joins(:product).merge(Product.not_free_entry_scope)} –

+0

是的,對不起這個錯字,是否適合你? –