When to use self in Model?

varatis picture varatis · May 29, 2012 · Viewed 29.2k times · Source

Question: when do I need to use self in my models in Rails?

I have a set method in one of my models.

class SomeData < ActiveRecord::Base
  def set_active_flag(val)
    self.active_flag = val
    self.save!
  end
end

When I do this, everything works fine. However, when I do this:

class SomeData < ActiveRecord::Base
  def set_active_flag(val)
    active_flag = val
    save!
  end
end

The active_flag value doesn't change, rather it fails silently. Can someone explain?

I can't find any duplicates, but if someone finds one that's fine too.

Answer

DVG picture DVG · May 29, 2012

When you're doing an action on the instance that's calling the method, you use self.

With this code

class SocialData < ActiveRecord::Base
  def set_active_flag(val)
    active_flag = val
    save!
  end
end

You are defining a brand new scoped local variable called active_flag, setting it to the passed in value, it's not associated with anything, so it's promptly thrown away when the method ends like it never existed.

self.active_flag = val

However tells the instance to modify its own attribute called active_flag, instead of a brand new variable. That's why it works.