Forum: Ruby on Rails How can I access an attribute via a symbol?

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.
Pat M. (Guest)
on 2006-03-19 02:35
(Received via mailing list)
In my model I'd like to write a method that accesses the attributes by
name.  A very simple implementation would be

class MyModel < ActiveRecord::Base
  def get_value(attribute)
    return value_of_attribute
  end
end

Then I can call it with m.get_value(:name) to get the value of the
name column in the db.  I'm not sure what to put in for
'value_of_attribute' though.  How do I do that?

Pat
David F. (Guest)
on 2006-03-19 02:35
(Received via mailing list)
Just use the [] accessor:

model = MyModel.find(1)
value = model[:attribute_name]

Cheers!

-DF
Pat M. (Guest)
on 2006-03-19 02:35
(Received via mailing list)
What if I'm in the model?

I don't want to just get the value of course..I want a method that
will take the name of the attribute, process it a bit, and give the
output.

Pat
Trevor S. (Guest)
on 2006-03-19 03:14
(Received via mailing list)
Hey Pat,

if you just want to get the value out of the AR attributes hash you
use self[]

(in your model)

def upcase_something(sym)
   self[sym].upcase
end

Regards,
Trevor
--
Trevor S.
http://somethinglearned.com
This topic is locked and can not be replied to.