Reputation: 4013
I have the following query
model = (1,2,3,4)
@posts = Post.where(category_id: id, product_model_id: model)
My above query is justing taking the 1
from model how can i use where in
condition over here
Edit-1
This piece of code works but I don't feel this as a good code right?
@posts = Post.where("category_id = ? and product_model_id in (#{model})", id)
Edit-2
If I use
@posts = Post.where("category_id = ? and product_model_id in (?)", id, model)
Throwing error as
invalid input syntax for integer: "15,16"
because my input is like this
select * from posts where category_id=5 and product_model_id in ('15,16')
How to correct it then..
Upvotes: 18
Views: 46048
Reputation: 9762
model_ids = model.split(",").map(&:to_i)
@posts = Post.where(category_id: id, product_model_id: model_ids)
or
model_ids = model.split(",").map(&:to_i)
@posts = Post.where("category_id = ? AND product_model_id IN (?)", id, model_ids)
Upvotes: 36
Reputation: 15965
According to the rails guide, you can pass in an array to where
and it should understand that you want to use IN. See the guide here: http://guides.rubyonrails.org/active_record_querying.html#subset-conditions
I'm a little confused by your syntax, since model = (1, 2, 3, 4)
doesn't look like valid array syntax.
Relevant part of the guide:
Client.where(orders_count: [1,3,5])
Upvotes: 26
Reputation: 13354
You could use arel, but I'd just do something like:
@posts = Post.where("category_id = ? AND product_model_id IN (?)", id, model)
Upvotes: 5