Forum: Ruby on Rails When to use self[:foo] in models

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
181976602397443ce119909b9d82cae2?d=identicon&s=25 blinking bear (Guest)
on 2007-05-15 17:28
(Received via mailing list)
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!
Bd2d12f85f54f93d3c9e2f558a593024?d=identicon&s=25 Mark Thomas (markthomas)
on 2007-05-15 20:00
(Received via mailing list)
> 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.
This topic is locked and can not be replied to.