Reputation: 76
I have a method which is taking optional arguments. And in the method I am doing query on the optional arguments like this:
def filter_element(param1, *param2)
param2[0].empty? ? filtered_element = Model_class.where('city = ?', param1) : filtered_element = Model_class.where('city = ? and price <= ?', param1, param2[0].to_i)
end
This is an example with one optional arguments passed into the method.
My question is, if i have more than one optional arguments and want to use it in the query arguments depending on its presence, how can I do that?
I know i can use if, elsif etc. But I want to use a DRY way to do it.
I am pretty sure there is a way, but couldn't find anything related to it.
Upvotes: 0
Views: 98
Reputation: 588
I think this can be done differently
#it's better to pass arguments not like array, but as hash
def filter_element(city, options = {})
scope = Model_class.where(city: city)
scope = scope.where('price <= ?', options[:price].to_i) if options[:price].present?
#some more scope limitation here
scope
end
element = filter_element('Minsk', price: 500)
Upvotes: 1