Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 333
Prabhakaran Avatar asked Nov 23 '13 19:11

Prabhakaran


People also ask

What does .take do in Rails?

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.

What does where return rails?

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.

What is eager loading in Rails?

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.


1 Answers

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)
like image 137
bjhaid Avatar answered Oct 12 '22 03:10

bjhaid