Rails – Create Some Simples Search Methods in ActiveRecord

Previously i have created a countries table which contains a country name and country code field. Get more information in the following link.
Rails – Preset Data in Database by Seed Fu
 

So now i want to create some simple search methods in app/models/country.rb. The ActiveRecord provides a very good API for us to work with the Model. Basically we could retrieve data by the find() and where() methods. The find() method returns a specific object while the where() method returns an array of objects. Both the following 2 methods could return a country name with reference to the input country code.
country.rb

...
def self.getCountyNameByCountryCode1(code)
  country = Country.find_by_code(code)
  return country.name
end

def self.getCountyNameByCountryCode2(code)
  country = Country.where(:code => code)
  return country[0].name
end
...

 

In the above example, i used find_by_code(:code) instead of the basic find(:id) method which . ActiveRecord automatically create those basic find_by_<field>() methods.

Done =)

Reference:

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.