Thursday, June 9, 2011

Active Record - finder Methods : Dynamic finder Method (Specialized Finder)

Dynamic Finders Method (Specialized Find )

Dynamic finders are a method of finding information based on particular database field of a table. For every field (also known as an attribute) you define in your table, Active Record provides a finder method

There are 4 types of dynamic finders which can be used:

  • find_by_XXX methods: Finds the first row for a given database field name(s).
  • find_all_by_XXX methods: Finds all the rows that satisfies a given database field name(s).
  • find_or_initialize_by_XXX: Finds a row with a given parameter(s) and if it does not exist will act similarly to calling new with the arguments you passed in.
  • find_or_create_by_XXX methods: Finds a row with particular parameters and if not available, then will be created in the database with the input parameters and then returned.

You can do find_last_by_* methods too which will find the last record matching your argument.

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 Product.find_by_name!("Ror")

1 comment:

  1. Nice article, these what i needed to fill my knoledges