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..
The Take method returns a record without any implied order. You can also specify a parameter, for example, #take(5) which will return the number of records you have specified in your parameter. If you don't care about the order or if you want an arbitrary record, #take is a good way to go.
where returns an ActiveRecord::Relation (not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation. find (and its related dynamic find_by_columnname methods) returns a single model object.
Eager loading is a way to find objects of a certain class and a number of named associations. Here I share my thoughts on using it with Rails. What are N + 1 queries? It mainly occurs when you load the bunch of objects and then for each object you make one more query to find associated object.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With