[英]How can I find object by an attribute other than id in Rails?
I need to find multiple models in my db by a unique identifier that is not the id. 我需要通过不是ID的唯一标识符在数据库中找到多个模型。 Is there a way to do this in rails?
有办法做到这一点吗? Basically, I'm looking for the analog of:
基本上,我正在寻找类似物:
Foo.find([1,2,3])
for the by_attribute helpers: 对于by_attribute助手:
Foo.find_by_name(['me','you','him'])
The issue I'm having now is that the find_by_name
helper is appending LIMIT 1
to the query it creates so I'm just getting one object back rather than an array of all of the objects I'm looking for. 我现在遇到的问题是
find_by_name
帮助程序将LIMIT 1
附加到它创建的查询中,因此我只是找回一个对象,而不是我要查找的所有对象的数组。
Thanks! 谢谢!
Using rails 3.x: 使用rails 3.x:
Foo.find_all_by_name(['me','you','him']);
Or using rails 4.x 或使用rails 4.x
Foo.where(name: ['me','you','him'])
As usual, I figured this out as soon as I'd written up the question for Stack Overflow :) 和往常一样,我在为Stack Overflow编写问题时就想出了这一点:)
where
supports a list of values and will return all objects that match. where
支持值列表,并将返回所有匹配的对象。 So, to find all Foos
by name: 因此,
Foos
名称查找所有Foos
:
Foo.where(name: ['me','you','him'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.