Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data to IN query in rails 3

I am working on rails 3 and sqlite db. Using a IN query. Currently passing an string variable of items to IN query. But While executing that query it takes '' so it's not working. How to get over this situation?

Here is my code

items = ""
items << "#{@invitation_user1.id}" << "," << "#{@invitation_user2.id}" << "," << "#{@user1.id}" << "," << "#{@user2.id}" << "," << "#{@user2.id}" << "," << "#{@profile1.id}" << "," << "#{@profile2.id}"
@activities = Version.where("item_id IN (?)","#{items}") 

Tried items.to_i, items.to_s but didn't work. In log i can see this.

SELECT "versions".* FROM "versions" WHERE (item_id IN ('19,20,4,1,1,4,1'))

But all i need is

 SELECT "versions".* FROM "versions" WHERE (item_id IN (19,20,4,1,1,4,1))
like image 514
chaitanya Avatar asked Mar 26 '12 06:03

chaitanya


People also ask

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.

What are active records in Rails?

Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.


2 Answers

You can just pass an array in. Rails is clever enough to to the right thing with it:

items = [
  @invitation_user1.id,
  @invitation_user2.id,
  @user1.id,
  @user2.id,
  @profile1.id,
  @profile2.id
]

@activities = Version.where("item_id IN (?)", items)
# or equivalently:
@activities = Version.where(:item_id => items)

This is vastly preferred over your variant, as Rails properly handles escaping of all passed values for the used database adapter.

like image 131
Holger Just Avatar answered Oct 15 '22 21:10

Holger Just


Use array instead of string.

For example

ids = [ @invitation_user1.id, @invitation_user2.id, @user1.id, @user2.id ]

Then easily you can find the records by

@versions = Version.find_all_by_id(ids)

This will result the query you expected.

SELECT "versions".* FROM "versions" WHERE (item_id IN (19,20,4,1))
like image 26
Soundar Rathinasamy Avatar answered Oct 15 '22 20:10

Soundar Rathinasamy