1

I have the following code that works but Im slightly confused as to why.

before_save :generate_slug

def generate_slug
  self.slug = [id, title.to_url].join('-')
end

I was under the impression that using self on a model method would be a Class method whereas this information is clearly being saved to an Instance, is this correct?

If I remove self from the self.slug the method doesn't work and slug is nil.

So if I need self.slug for the method to work should be using self on self.id & self.title.to_url as well?

Sam Mason
  • 1,037
  • 1
  • 8
  • 29

1 Answers1

6

self in this case (within an instance method) refers to the actual instance object.

self in a method name (however) indicates the method is a Class method.

The self. is optional if you're referring to attributes, but is required when you're assigning attributes.

slug = [id, title.to_url].join('-')

creates a new local variable in the instance method

self.slug = [id, title.to_url].join('-')

updates the slug attribute of the object.

The reason you didn't need self for id or for title is because they weren't being assigned a value, just accessed, so the interpreter understands it has to get the model attributes.

SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53