Reputation: 888
I have written a scope to filter out results where 'free entry = true'. I want the scope to apply to a Products database as well as its child , 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) }
I know it works, I can scope it in rails console like so,
Product.where("free_entry = true")
I can scope the product model successfully, however when I try to apply the same scope to the job_product model, and use it in the controller it spits an error
Unknown column 'job_products.free_entry' in 'where clause'
How do I refine the scope to a child of the parent class.
Thanks
Upvotes: 0
Views: 440
Reputation: 23949
Your error is because you're using a Object.property
as a key in a hash, that's not valid syntax. What you need to do is tell it to join the Products table, and then you can re-use the Product's scope with merge
.
Try this:
class JobProduct
...
scope :not_free, -> { joins(:product).merge(Product.not_free_entry_scope) }
...
end
Upvotes: 3