Eric
Eric

Reputation: 115

Rails - how to make query parameters optional in Model?

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

Answers (2)

Bartłomiej Gładys
Bartłomiej Gładys

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

user3033467
user3033467

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

Related Questions