find_by
suggest changeYou can find records by any field in your table using find_by.
So, if you have a User model with a first_name attribute you can do:
User.find_by(first_name: "John")
#=> #<User id: 2005, first_name: "John", last_name: "Smith">
find_by does not raise when nothing matches. It returns nil. If several rows match, it returns the first one.
Use find_by! when you want an ActiveRecord::RecordNotFound error, the same error find raises.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents