Reputation: 11040
I'm trying to write a validator that will only update the price of a book if the selling status is inactive.
# frozen_string_literal: true
class BookPriceValidator < ActiveModel::Validator
def validate(record)
record.errors[:price] << "can't change price on book" if record.selling == "active"
end
end
The problem I'm running into right now is that the error gets called even when the book price is not updated. How can i call this error only when the :price field has actually changed?
Upvotes: 0
Views: 48
Reputation: 29478
You can change the condition to
if record.price_changed? && record.selling == "active"`
ActiveModel::Dirty keeps track of the unpersisted changes made to an ActiveRecord
object and adds convenience methods for each attribute as [attribute_name]_changed?
. So all you have to do is check if the price changed along with your current condition.
Upvotes: 1