1

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?

2

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What I keep getting when i try to do this is WHERE "users.age <= 20" so it's inserting double quotes around the whole clause. I think the issue is i have several clauses stored in an array, which is being passed to where() instead of passing a single string with the value as the second param.
@xd6_ See my updated answer. You can easily chain your where clauses for multiple conditions like above. Let me know if you have any other question.
@xd6_ Please look at my Update_3, I think this will work for you. Let me know if not!
1

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'

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.