Thursday, June 9, 2011

Active Record - finder Methods : Custom finder Method (Customized Finder)

This method uses writing custom find* methods which could be either un-conventional method or override the methods declared by the ActiveRecord::Base. Custom finders are declared in the Model objects and are generally tagged by self keyword.

Custom finders are nothing but writing find methods within the Model and call the ActiveRecord::Base::Find* methods from these methods. Custom finders generally are self methods declared in the Model object.

#Product.rb — Model file

def self.find_product_by_status(status)
if status != :o utofshelf
Product.find_by_sql ["SELECT * FROM product WHERE status=?",status]
else
Product.find_by_sql ["SELECT * FROM product WHERE status= 'outofshelf' AND availability=false"]
end
end

The example above identifies a custom finder where it checks if the status is not out of shelf, then get all the products based on the status and if it is out of shelf, then check the status and also is not available. Also if you see the name of the find method it is an un-conventional name find _product_by_status instead of find_by_status.

Developers can utilize custom finder to name methods by thier own way or even custom finders can also be used to over write the method names which exists in the ActiveRecord::Base class. An example can be found as follows:

#Product.rb — Model file

def self.find_by_status(status)
if status != 'outofshelf'
Product.find_by_sql ["SELECT * FROM product WHERE status=? AND availability=false"]
else
super
end
end

In this example, you see that the custom finder has the same name as a find_by_status method which is a standard ActiveRecord::Base method and has been overwritten by the find method in the Model file. In the example, we have also dealt in re-directing the custom finder method back to its parent method by using the super keyword.

No comments:

Post a Comment