When to use self[:foo] in models

I’ve always been a little unclear on accessing attributes of an
ActiveRecord
model within the class itself, i.e.

def full_name
“#{first_name} #{last_name}”
end

or

def full_name
“#{self[:first_name]} #{self[:last_name]}”
end

This is a contrieved example and I think both work, but I’ve found other
times where doing something similar doesn’t work without the self[:].
Can
someone shed some light on what the difference is?

Thanks!

This is a contrieved example and I think both work, but I’ve found other
times where doing something similar doesn’t work without the self[:]. Can
someone shed some light on what the difference is?

I think it’s preferable to use the methods rather than the hash
interface. The only situation I’ve come across where you cannot use
the method is single-table inheritance, where you have to use
self[:type] instead of type because type is a built-in (though
deprecated) method.

  • Mark.