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