Some Interesting Dynamic Finders

find_or_create_by_X: As obvious by name this dynamic finder method allows you to find or create a new record on the basis of attributes passed. A very good example by DHH himself goes like this…

class Account < ActiveRecord::Base
    has_many :people do
      def find_or_create_by_name(name)
        first_name, *last_name = name.split
        last_name = last_name.join " "

        find_or_create_by_first_name_and_last_name(first_name, last_name)
      end
    end
  end

 person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson")
 person.first_name # => "David"
 person.last_name  # => "Heinemeier Hansson"

find_or_initialize_by_X : This new method in available in edge rails now. Its almost similar to the find_or_create_by_X finder. The basic difference is that this method unlike find_or_create_by_X only initialize the object and do not saves it.

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

del.icio.us Digg it reddit Yahoo MyWeb
blog comments powered by Disqus