Reputation: 289
i have a page with filters and it doesn't work properly, it works if all filters are set. But if category filter isn't set and the other two are set it wont work(it shows all products). the same as before if category is set and the price is not stock is set again , it shows thing filtered only by category. my model is product.rb
def self.categorized(category=nil)
return self.where("category_id LIKE ?",category ) if category
self
end
def self.priced(price=nil)
return self.where("price < 50") if price=="low"
return self.where("price < 100 and price > 50") if price=="mid"
return self.where("price > 100") if price=="high"
self
end
def self.stocked(stock=nil)
return self.where("stock > 0") if stock=="available"
return self.where("stock = 0" ) if stock=="out"
self
end
def self.catalog(params)
page = params[:page]
category = params[:category]
stock = params[:stock]
price = params[:price]
self.stocked(stock).priced(price).categorized(category)
.paginate(:page =>page).limit(9)
end
Upvotes: 0
Views: 68
Reputation: 3709
Use scope for this,
scope :priced, where("price < 50")
scope :stocked, where("stock > 0")
Then call Product.priced.stocked
.
Read more about scope and how to pass variables to scope here
Edit:
This will be your complete code for filtering.. Let me know if this is working or not.
scope :categorized, (lambda do |category|
where("category_id LIKE ?",category ) if category
end)
scope :priced, (lambda do |price|
where("price < 50") if price=="low"
where("price < 100 and price > 50") if price=="mid"
where("price > 100") if price=="high"
end)
scope :stocked, (lambda do |stock|
where("stock > 0") if stock=="available"
where("stock = 0" ) if stock=="out"
end)
def self.catalog(params)
page = params[:page]
category = params[:category]
stock = params[:stock]
price = params[:price]
@products = Product.scoped
@products.stocked(stock) if stock
@products.priced(price) if price
@products.categorized(category) if category
@products.paginate(:page =>page).limit(9)
end
Upvotes: 2
Reputation: 5651
Your problem is that self
isn't exactly what you expect it to be. Since these are class level methods self
always refers to the 'plain' class, not something that has already 'aggregated' the where clauses you use. What you want here is to return something that doesn't change the chained query you have so far.
def self.categorized(category=nil)
return self.where("category_id LIKE ?",category ) if category
scoped
end
should work
(Updated my answer, not sure if the Product.none did what I thought it would and it is available only for Rails 4.0).
Upvotes: 3