作者:mobiledu2502936451 | 来源:互联网 | 2023-01-27 13:27
Iamworkingonrails3andsqlitedb.UsingaINquery.Currentlypassinganstringvariableofite
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?
我正在使用rails 3和sqlite db。使用IN查询。当前将项的字符串变量传递给IN查询。但是在执行该查询时需要''因此它不起作用。如何克服这种情况?
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.
尝试过items.to_i,items.to_s但是没有用。在日志我可以看到这一点。
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))
3 个解决方案
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?
无论如何,获取ID的方式很奇怪,因为......如果添加更多用户会发生什么?或个人资料?
What I would do (seeing as little as we can see in your example)
我会做什么(在你的例子中我们看到的很少)
items = Array.new
items <
and later define those methods, as in:
然后定义这些方法,如:
def get_invitation_user_ids
InvitationUser.select(:id).map(&:id)
end
...