Rails 4 how to use where and where are able to simultaneously

I have the following request

model = (1,2,3,4) @posts = Post.where(category_id: id, product_model_id: model) 

My above query is trying to take 1 from the model, how can I use the where in condition here

Edit-1

This part of the code works, but I do not think this is 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)

Throw error like

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 fix it then ..

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

or

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

According to the guide on guides, you can pass an array to where , and it should understand that you want to use IN. See the manual 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) does not look like syntax syntax.

Relevant part of the manual:

 Client.where(orders_count: [1,3,5]) 
+14
source

You can use isl, but I would just do something like:

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

+2
source

Source: https://habr.com/ru/post/958703/


All Articles