For our application I am newly creating records in two ways:
- With the default values in the database.
- Manually setting attributes.
I need to distinguish between these changes so that I know whether the attribute is manually overridden, or whether it was set because it was the default.
I am using the before_validation callback on: :create with a method that checks changes, but this method can't differentiate between the two scenario's. These two lines are equal when it concerns the changes method (I'm using Minitest and FactoryBot to get my point across):
# Table name: users
# admin :boolean default(FALSE), not null
FactoryBot.create(:user, admin: false)
FactoryBot.create(:user)
Is there a way I can make the distinction anyway?
One trick uses the fact that that Rails doesn't use the setter method if the value is provided by the default. So you could override the setter and set some other attribute to indicate this was set by the caller:
Added advantage of also working for: