Rails:如何在任意索引上使用 find 方法
我创建了一个模型,其中有一个字符串作为唯一标识符。 我创建了一个迁移来在该字符串上添加索引并将其设置为唯一。 我如何通过将其唯一标识符字符串传递给 find 方法来访问数据库条目,例如
@object = Object.find(params[:unique_id])
目前,我得到的只是 ActiveRecord::RecordNotFound 异常...
找不到 id=abc 的对象
...当我尝试访问 Object.find('abc')
时,
where
方法是没有替代选择的,因为这给了我返回一种关系。
I have created a model that has a string as a unique identifier.
I created a migration to add an index on that string and set it to be unique.
How can i access a database entry by just passing its unique identifier string to the find method, for example
@object = Object.find(params[:unique_id])
At the moment, all i get is an ActiveRecord::RecordNotFound exception...
Couldn't find Object with id=abc
...when i try to access Object.find('abc')
The where
method is no alternative as this gives me back a relation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Object.find(:unique_id)
在“object_id”列上搜索;如果您想搜索其他列,请使用Object.find_by_[column_name]!(:unique_id)
。如果找不到记录,这将引发异常,就像find
方法一样。Object.find(:unique_id)
searches on the column 'object_id'; If you want to search on an other column, useObject.find_by_[column_name]!(:unique_id)
. This will raise an exception if the record can't be found, as would do thefind
method.