Rails: How to use the find method on an arbitrary index
-
20-04-2021 - |
Вопрос
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.
Решение
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.
Не связан с StackOverflow