Rails:如何在任意索引上使用 find 方法

发布于 2024-12-29 05:49:48 字数 378 浏览 4 评论 0原文

我创建了一个模型,其中有一个字符串作为唯一标识符。 我创建了一个迁移来在该字符串上添加索引并将其设置为唯一。 我如何通过将其唯一标识符字符串传递给 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷爱 2025-01-05 05:49:48

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, use Object.find_by_[column_name]!(:unique_id). This will raise an exception if the record can't be found, as would do the find method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文