Consider a model user:
User(id: integer, name: string, email: string, status: string)
When I built the application, status was a field in the database. But new requirements means a change so that status is dynamically calculated in some cases. For example, on Sundays, if their last name starts with A, then their status is “not ok”.
I want to encapsulate this functionality in the User model with something like the following:
Class User < ActiveRecord::Base
def status
if is_sunday && last_name.starts_with('A')
return 'not ok'
else
return status
end
end
end
What is the best way to do this? If the above code does work, it seems bad practice to override the field in the database with a method.
Alternatively, I could create a method get_status to use the above code. But in this case I need to change every reference to status throughout the application. That doesn’t sound good.
I’ve seen in the ActiveRecord::Base documentation that you can override default accessors provided by ActiveRecord. Of course you can’t use
statusas you do because it makes the method somewhat recursive.You can access the column value in the DB by using
read_attribute(:attribute_name)orself[:attribute_name]if you prefer. So long story short, your accessor becomes:UPDATE: I’ve tried it and it works but pay attention because if you don’t call this method explicitly you get the DB content…for example you try to query the
userstable to find users withstatus = "not ok"you could have surprises.