簡體   English   中英

根據父模型布爾值過濾子模型

[英]filter child model based on parent model boolean value

我寫了一個作用域來過濾掉“免費入境=真”的結果。 我希望范圍適用於Products數據庫及其子級job_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) }

我知道它可以正常工作,我可以像這樣在Rails控制台中調整范圍,

Product.where("free_entry = true")

我可以成功確定產品模型的范圍,但是當我嘗試將相同的范圍應用於job_product模型,並在控制器中使用它時,會吐出錯誤

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

如何將范圍縮小為父類的子級。

謝謝

您的錯誤是因為您將Object.property用作哈希中的鍵,所以這是無效的語法。 您需要做的就是告訴它加入Products表,然后可以通過merge重復使用Product的作用域。

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM