Search code examples
ruby-on-rails-3models

Where to place a default value to return from a Model in Rails?


I have a model called City.

I have several methods that look for a City depending on different attribute (city close to zip code, city by population...etc). However, if a city is not found I want to default to a given city, let's say New York.

So I have found myself doing this a lot:

@city = City.find_by_zip_code(83030)
if @city.nil?
 @city = City.find_by_name('New York')
end

This is just in a method where I look by zip code, but I keep doing this in several methods. Where and how should I centralize this default:

City.find_by_name('New York')

EDIT:

Would it be a good idea to have a method like this:

def self.default_city
 @default_city = City.find_by_name('New York')
end

To avoid fetch the database everytime I want to get the default city?


Solution

  • You can at least make it easier to type out:

    @city = City.find_by_zip_code(83030) || City.find_by_name('New York')
    

    To avoid extra db hits, cache the default:

    def self.default_city
      Rails.cache.fetch('default_city') do
        City.find_by_name('New York')
      end
    end
    

    I have a blog post with a few more details about caching like that: http://www.tmatthew.net/blog/rails-caching-example