rails 4 how to use where and where in condition simultaneously

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


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)


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..


model_ids = model.split(",").map(&:to_i)
@posts = Post.where(category_id: id, product_model_id: model_ids)</code>


model_ids = model.split(",").map(&:to_i)
@posts = Post.where("category_id = ? AND product_model_id IN (?)", id, model_ids)

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])

You could use arel, but I'd just do something like:

@posts = Post.where("category_id = ? AND product_model_id IN (?)", id, model)

Need Your Help


oop yagni solid-principles

One of the most frequent arguments I hear for not adhering to the SOLID principles in object-oriented design is YAGNI (although the arguer often doesn't call it that):

What Does Question Mark Mean in Xcode Project Navigator?

xcode version-control

In the project navigator in Xcode, I am not sure what the ? is trying to tell me next to the file name.