0

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!

2
  • This has already been answered here: stackoverflow.com/questions/15474883/… Commented Sep 13, 2016 at 17:55
  • @omnikron thanks for pointing me to this direction ! Commented Sep 15, 2016 at 12:53

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.