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
Just use the [] accessor:
model = MyModel.find(1)
value = model[:attribute_name]
Cheers!
-DF
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
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