What is Dynamic Finders?

Technology CommunityCategory: Ruby on RailsWhat is Dynamic Finders?
VietMX Staff asked 3 years ago

For every field (also known as an attribute) you define in your table, Active Record provides a finder method.

  1. If you have a field called first_name on your Client model for example, you get find_by_first_name and find_all_by_first_name for free from Active Record.
  2. If you have a locked field on the Client model, you also get find_by_locked and find_all_by_lockedmethods.
  3. You can also use find_last_by_* methods which will find the last record matching your argument.
  4. You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an ActiveRecord::RecordNotFound error if they do not return any records, like Client.find_by_name!("Ryan")

If you want to find both by name and locked, you can chain these finders together by simply typing and between the fields. For example, Client.find_by_first_name_and_locked("Ryan", true).