I have scope
scope :for_list, lambda { |brand_ids|
where('brands.id IN (?)', brand_ids).includes(:models).where("models.popular = '1'").order('mo开发者_如何学编程dels.name')
}
But some times there are no models.popular = 1
And in this case I want to select all from models ignoring popular
parameter
How to write that scope?
Since it's simply a lambda function, you can use an if/else
in there and it'll get evaluated at the time it's called. Therefore, you could write the scope like this:
scope :for_list, lambda { |brand_ids|
if self.popular > 1
where('brands.id IN (?)', brand_ids).includes(:models).where("models.popular = '1'").order('models.name')
else
where('brands.id IN (?)', brand_ids).includes(:models).order('models.name')
end
}
That should work. However, I'd caution against using this. That logic doesn't belong in a scope. Instead, you should question you your views and controllers are set up and rework those.
精彩评论