[英]Get all Rails records from an array of IDs
I have an array of record IDs ["303", "430", "4321", "5102"]
. 我有一个记录ID数组["303", "430", "4321", "5102"]
。 I want to get all records that match these IDs, using SQL: 我想使用SQL获取与这些ID匹配的所有记录:
acceptable_ids = ["303", "430", "4321", "5102"]
@users = User.where("is_awesome = true AND id IN acceptable_ids)
Gives this error: 给出此错误:
ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR: syntax error at or near "["
What is the correct way to write my query to get all users with ids that match acceptable_ids
? 编写我的查询以获取所有ID均与acceptable_ids
匹配的用户的正确方法是什么?
Note: 注意:
I am aware of User.find(acceptable_ids)
, but can't use this since I am constructing a SQL query with select, where, and join clauses. 我知道User.find(acceptable_ids)
,但是由于我正在使用select,where和join子句构造一个SQL查询,因此无法使用它。
User.where(is_awesome: true, id: acceptable_ids)
You could do this. 你可以这样做。
@users = User.where("is_awesome = true AND id IN (#{acceptable_ids.join(', ')})")
I'm sure I've seen a simpler way but can't recall it at the moment... but above should work. 我敢肯定,我已经看到了一种更简单的方法,但是目前无法回忆起……但是上面的方法应该可行。
EDIT 编辑
However, you can see from the vociferous comments that this is not a popular answer, so you should look at some of the alternatives linked and listed, eg 但是,您可以从激烈的评论中看到这不是一个流行的答案,因此您应该查看链接和列出的一些替代方法,例如
# Will raise exception if any value not found
User.find( [1,3,5] )
# Will not raise an exception
User.find_all_by_id( [1,3,5] )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.