I have a Picture class and I want to override returning the “description” database column value depending on some logic.
Is this valid in Rails? Can I always rely on the Class to call the class method before returning the database column value?
# database columns for Picture class
# description => String
# parent_id => Integer
class Picture < ActiveRecord::Base
def description
if parent_id.nil?
self.description
else
description = Picture.find(parent_id).description
end
end
end
Couldn’t figure out where to find the answer in the Rails source code so any help would be appreciated.
Thanks!
EDIT
I’m trying to return a Picture’s description depending on whether or not it’s a child or parent Picture (they can be nested). The example is a bit contrived…I could easily avoid this by using a method without the same name as the database column…such as
def my_description
if parent_id.nil? # return db data since no parent
self.description
else # return parent's description if one exists
description = Picture.find(parent_id).description
end
end
I guess I’m trying to be unnecessarily complicated here
It’s not totally clear what you’re trying to do, but you can use super to get the description value from within the method:
Note that I changed the last line to use
self.description =because I’m assuming you want to set the description value. If that’s not the case, then you don’t need to assign it to any variable.