Monday, March 23, 2015

Caveat to omitting `self` in Model method calls

I wanted to add a caveat to something I stated in a previous post about leaving self out when calling methods from inside other methods in a model. This WILL give you problems if you are trying to assign values to a Model attribute.

For example, doing this:

  def change_object_name
    name = "Steve"
  end

All this is doing is setting a local variable called name equal to "Steve." If your Model has an attribute called name and you want to set it, you have to use self.name:

  def change_object_name
    self.name = "Steve"
    # Oh, and don't forget to save!
    save
  end

No comments:

Post a Comment