so i have a model named item that has a column named price. I assumed that columns would be stored as instance variables inside models but the method
def price
@price
end
returns nothing. so my question is how do i access price from inside the model?
extra info my reason for doing this is items sometimes have specials so i want a method price that checks for specials and changes the price if a special is active and leaves it alone if not, something like
def price
check_for_special
@price
end
ActiveRecord automatically generates the setter and getter methods associated with a database field. price
will be the getter method for the field of the same name.
By adding a price
method you have overwritten the method created by ActiveRecord. As you are overwritting an existing method, you can access the original method by calling super
. So you could to this:
def price
check_for_special
super
end
However, I'd not recommend doing that, as you usually need a method of just getting the price value, without it always calling another method. So
def price_with_check
check_for_special
price
end