xd6_
xd6_

Reputation: 483

Activerecord where array with less than condition

I have an array of conditions i'm passing to where(), with the conditions being added one at a time such as

conditions[:key] = values[:key]
...
search = ModelName.where(conditions)

which works fine for all those that i want to compare with '=', however I want to add a '<=' condition to the array instead of '=' such as

conditions[:key <=] = values[:key]

which of course won't work. Is there a way to make this work so it i can combine '=' clauses with '<=' clauses in the same condition array?

Upvotes: 1

Views: 1074

Answers (2)

ReggieB
ReggieB

Reputation: 8212

You could use arel.

conditions = {x: [:eq, 1], y: [:gt, 2]}

model_names = ModelName.where(nil)

conditions.each do |field, options|
  condition = ModelName.arel_table[field].send(*options)
  model_names = model_names.where(condition)
end

model_names.to_sql --> 'SELECT * FROM model_names WHERE x = 1 and y > 2'

Upvotes: 1

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34318

One way of doing it:

You could use <= in a where clause like this:

   User.where('`users`.`age` <= ?', 20)

This will generate the following SQL:

SELECT `users`.* FROM `users` WHERE (`users`.`age` <= 20)

Update_1:

For multiple conditions, you could do this:

User.where('`users`.`age` <= ?', 20).where('`users`.`name` = ?', 'Rakib')

Update_2:

Here is another way for multiple conditions in where clause:

User.where('(id >= ?) AND (name= ?)', 1, 'Rakib')

You can add any amount of AND OR conditions like this in your ActiveRecord where clause. I just showed with 2 to keep it simple.

See Ruby on Rails Official Documentation for Array Conditions for more information.

Update_3:

Another slight variation of how to use Array Conditions in where clause:

conditions_array = ["(id >= ?) AND (name = ?)", 1, "Rakib"]
User.where(conditions_array)

I think, this one will fit your exact requirement.

Upvotes: 1

Related Questions