Reputation: 115
I am trying to build a filter area on my index with multiple parameters. My problem is that I don't know how to make each of them optional if I need to. I mean, even if I don't set a value to a field, I want my filter to only work with the ones I filled.
I wrote this code which works well, except when I remove one or several parameters.
def self.filter(type, min, max, start_at, end_at)
where(type => min..max, :first_date => start_at..end_at).order("#{type}": :desc)
end
I know I can use scope
but as I am new to Rails, it's pretty unclear. If somebody can come with some hints? Thanks!
Upvotes: 0
Views: 1398
Reputation: 4615
You can atrriubte these to nil
def self.filter(type =nil, min=nil, max=nil, start_at=nil, end_at=nil)
a = YourModel
a = a.where(type => min..max) if min.present? && max.present?
a = a.where(first_date: start_at..end_at) if start_at? && end_at.present?
a = a.order("#{type}#": :desc) if type.present?
a
end
Upvotes: 2
Reputation: 1188
You could chain multiple where
result = where(type => min..max)
result = result.where(first_date: start_at..end_at) if start_date && end_date
return result
Upvotes: 0