How to issue a 'find' or 'where' that raises a RecordNotFound
For anyone coming across this question, now you have the method find_by!
that does exactly what the OP asked for the find
case.
example:
Foo::Bar.find_by!(name: "CocktailBar")
https://apidock.com/rails/v4.0.2/ActiveRecord/FinderMethods/find_by%21
In the last snippet of code you are actually fetching all records from DB and then doing select
on a Ruby array. It has nothing to do with ActiveRecord
, so you can do whatever you like to raise exception manually, either use the code suggested by Douglas, or if
, or unless
etc. But it seems that you don't quite understand what your code does. Your select {...}
is not translated into SQL SELECT ... WHERE(...)
.
If you need an exception raised automatically by ActiveRecord
query, use this:
Foo::Bar.where([ "lower(name) = ?", name.downcase ]).first!
The equivalent bang methods exist for find_by methods as well, for example Foo::Bar.find_by_name!(name)