0

For example we have model TableRow - columns (:account_number, :month, :department, :phone_number). And have a method that returns filtered rows by arrays of this params. For required params we can use

TableRow.where('account_number IN (?)', param) 

Is there best way to add in this query unrequired params (department, phone_number) that can be nill and we should return records with any params in this column?

2 Answers 2

2

There are a couple ways to approach this. If you want your query to be static, you can check the literal value of your param with the SQL logic itself:

TableRow.where('COALESCE(:depts) IS NULL OR department IN (:depts)', depts: param) 

You can also build up your relation incrementally in Ruby:

relation = TableRow.all relation = relation.where(department: depts) if depts.present? 
Sign up to request clarification or add additional context in comments.

1 Comment

The way with COALESCE is very helpful for me. Thank you.
0

Your question is hard to understand, but if what you want is to filter by phone_number while still retrieving records where phone_number is null, you just have to that:

TableRow.where('phone_number IN (?)', param << nil) 

1 Comment

This won't work. c in (v1, v2) is equivalent to c = v1 or c = v2 but X = null evaluates to null for all X (even when X is null) and null isn't truthy in SQL. You're also modifying param and that's generally a bad idea.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.