Reputation: 83
Takes a query using some methods like code bellow. How can I ignore the nil
values? For example: if the method date
returns nil
I wanna that the query use just array_one
and array_to
.
def array_one
...
end
def array_two
...
end
def date
...
end
Record.where(array_one: array_one, array_two: array_two, date: date)
Upvotes: 2
Views: 1094
Reputation: 2947
Record.where({ array_one: array_one, array_two: array_two, date: date }.compact)
Upvotes: 4
Reputation: 106802
I would do something like this:
scope = Record.scope
scope = scope.where(array_one: array_one) if array_one
scope = scope.where(array_two: array_two) if array_two
scope = scope.where(date: date) if date
scope
Upvotes: 3
Reputation: 13407
You can chain your queries together (it's called lazy loading). They won't actually be executed until the first thing that calls query. This allows you to 'build' the query
query = Record.where(array_one: array_one, array_two: array_two)
query = query.where(date: date) if date.present?
query.each do |row| # now the query is executed
# do stuff
end
Upvotes: 4