(no title)
jonathanhefner | 6 years ago
So the final code from the article would look like:
class ProductSearch < TalentScout::ModelSearch
criteria(:search) { |search| where("title ILIKE '%?%'", search) }
criteria(:from_price) { |from_price| where("price > ?", from_price) }
criteria(:to_price) { |to_price| where("price < ?", to_price) }
criteria(:properties) { |properties| joins(:product_properties).where(property_id: properties) }
criteria(:category_id) { |category_id| where(category_id: category_id) }
order :price, default: :desc
end
Brevity is an obvious benefit, but reliability even more so. For example, the code in the article has at least two major mistakes:1) `from_price` will silently never be applied
2) `sort_type` and `sort_direction` defaults are mixed up and always nil, either of which will raise an exception, but only when the corresponding request params are omitted
Another benefit of using the gem: instances of the `ProductSearch` class from above can be used with the stock Rails form builder (i.e. `form_for` and `form_with model:`).
No comments yet.