Reputation: 59
EDIT
Here's the working syntax...
Model.where('name like ?', "%#{q}%").where('value > ?', c)
or
Model.where("name like (?)","%#{q}%").where("value > ?",c)
Thanks to posters for their help with this.
Original Question
I'm having trouble understanding active record syntax.
Here's what i'm trying to do
q = "John"
c = 50
Model.where('name like ? AND value > ?', "%#{q}%", "%#{c}%")
This is the wrong syntax.
What i'm trying to achieve is
name like John AND value greater than 50
How do i chain different types of queries together in ActiveRecord?
Thanks.
Upvotes: 0
Views: 980
Reputation: 3915
For Rails 3 using AREL,
ut = User.arel_table
users = User.where(ut[:name].matches("%#{q}%").and(ut[:value].gt(c)))
# SELECT "users".* FROM "users" WHERE ("users"."name" LIKE '%John%' AND "users"."value" > 50)
Upvotes: 1
Reputation: 549
Don't quote q and c:
Model.where('name like ? AND value > ?', q, c)
Rails automatically converts the variables to an appropriate string for you.
Chaining refers to chaining of the where(), select(), order() functions, eg, this is equivalent to above:
Model.where('name like ?', q).where('value > ?', c)
If you want to include the % wildcard for the like bit only, you can do:
Model.where('name like ?', "%#{q}%").where('value > ?', c)
Upvotes: 4
Reputation: 6942
You can try Model.where("name like (?)","%#{q}%").where("value > ?",c)
. Or used scope to help further to easy to chain
Upvotes: 1