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:
