简体   繁体   English

如何在Rails中通过ID以外的属性查找对象?

[英]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.

相关问题 Ruby on Rails 按 ID 以外的字段查找 - Ruby on Rails Find By Field other than ID 在 Rails 中,除了验证错误之外,如何找出导致 .save() 失败的原因? - In rails, how can I find out what caused a .save() to fail, other than validation errors? 如果存在基于记录ID以外的属性的特定记录,Ruby on Rails如何创建新记录或更新? - How to create a new record or update if a particular record based on an attribute other than record id exists, Ruby on Rails? 如何将 rails 代码添加到 div 标签中的 id 属性? - How can I add rails code to id attribute in div tag? Rails-find_by列(除“ id”以外)结果为“ null” - Rails - find_by column other than “id” results in “null” Rails 通过显示页面的 id 以外的其他内容查找 - Rails find by something other than id for show page Ruby on Rails:我可以使用ID以外的属性/列删除记录吗? - Ruby on Rails: Can I delete records using attributes/columns other than ID? 我可以在rails视图中使用link_to之外的其他内容吗? - Can I use something other than id with link_to in my rails view? 如何在Rails 4的最后显示嵌套对象属性 - How can I display an nested object attribute on last in Rails 4 如何在 id 以外的 Rails 活动记录中创建唯一列 - how to make a unique column in rails active records other than id
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM