Dynamic find_by Methods


Rails (ActiveRecord) allows/provide dynamic find methods. Dynamic finder is shorten and simplest way to improve readability of rails sql query.  If you have a field called fname and lname in user model. we can write

@user = User.find_by_fname(‘xxxx’)  Or  @user = User.find_all_by_fname(‘xxxx’)

INSTEAD OF

@user = User.find(:all , :conditions => [“fname =?”, ‘xxxx’])

Real picture of dynamic find comes when we have multiple conditions. like

@user = User.find(:all , :conditions => {:fname => ‘xxxx’, :lname => ‘yyyy’})

we simplify this query by

@user = User.find_by_fname_and_lname(‘xxxx’, ‘yyyyy’)

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.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s