Go to content Go to menu

Here’s a little one that got me in the past. When you’re writing a method of a model, you have to be careful about how you set attributes.

Let’s say for example that you have a model Country, with attributes population, area, and government. When you want to use this property in a method, you can say:

Country
  def population_density
    area / population
  end
end

And this will work just fine. So, it seems like you can use the area and population in your code when you need to deal with these attributes.

Watch Out!

Look out that you don’t do this in the method:

Country
  def plague
    government = 'anarchy'
    population = 0
    save
  end
end

The problem is that population = 0 will only set a local variable to 0, and not your population attribute. Instead, you have to use self.population = 0. So, your #plague method would look like this:

def plague
  self.government = 'anarchy'
  self.population = 0
  save
end

Disclaimer:

Yes, I know, #plague would really look like this:

def plague
  update_attributes :government => 'anargy', :population => 0
end

I used the example above to demonstrate the concept.