Filip Bartuzi
Filip Bartuzi

Reputation: 5931

Rails.where Greater/Lesser Than without writing SQL statements

So I have DB query

ageVariable = 36
Actor.where("age > ?", ageVariable)

is that possible to avoid ? syntax?

I'm looking for :key based solution that would look something like this:

Actor.where(age: greater_than(age_variable) or ...where(age: > age_variable)

Edit:

In response to @bounty answer: Range doesn't solve problem.

Actor.where(:created_at => (1000000.years.ago..2.days.ago) sounds terrible

Upvotes: 2

Views: 158

Answers (3)

Andrey Deineko
Andrey Deineko

Reputation: 52357

You can use Arel to get it done without using raw SQL:

Actor.where(Actor.arel_table[:age].gt(36)).all

Upvotes: 4

yoppuyoppu
yoppuyoppu

Reputation: 490

ageVariable = 36
Actor.where("age > :target_age", target_age: ageVariable)

I avoided ? and made it look like the latter one ...where(age: > age_variable)...And I'm not even using between but greater than. Did I get closer to what you have in your mind?

Upvotes: 0

bunty
bunty

Reputation: 1098

You can use range condition for this.

ageVariable = (36..1000)
Actor.where(:age => ageVariable)

This will give all actor which are in between 36-1001

Upvotes: 0

Related Questions