简体   繁体   中英

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

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

What you are looking for is split :

[1] pry(main)> a = '19,20,4,1,1,4,1'
=> "19,20,4,1,1,4,1"
[2] pry(main)> a.split(',')
=> ["19", "20", "4", "1", "1", "4", "1"]
[3] pry(main)> a.split(',').map(&:to_i)
=> [19, 20, 4, 1, 1, 4, 1]

But, as you are constructing the 'string' manually, better to use an array:

items = Array.new
items << @invitation_user1.id << @invitation_user2.id << @user1.id
items << @user2.id << @user2.id << @profile1.id << @profile2.id
@activities = Version.where(item_id: items) 

Anyway, the way to get the ids is strange because... what would happen if you added more users? or profiles?

What I would do (seeing as little as we can see in your example)

items = Array.new
items << get_invitation_user_ids
items << get_user_ids 
items << get_profile_ids
@activities = Version.where(item_id: items)

and later define those methods, as in:

def get_invitation_user_ids
  InvitationUser.select(:id).map(&:id)
end

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM