Reputation: 15156
I have a model with attr_accessor
and I'm adding an error to this attr_accessor. Why does it valid? The code below is self-explainable, I think:
class Dealer < AR::Base
attr_accessor :keyword_data
def keyword_data=(file)
begin
parse_values(file)
rescue CSVKeywordsParser::ReadError => e
errors.add(:keyword_data, e.message)
end
end
end
>> dealer.errors
=> #<ActiveModel::Errors:0x007ff586359610 @base=#<Dealer id: 6, name: "Something">, @messages={}>
>> dealer.errors.any?
=> false
>> dealer.add :keyword_data, "xxx"
=> ["xxx"]
>> dealer.errors
=> #<ActiveModel::Errors:0x007ff586359610 @base=#<Dealer id: 6, name: "Something">, @messages={:keyword_data=>["xxx"]}>
>> dealer.errors.any?
=> true
>> dealer.valid?
=> true
How can I add error to attr_accessor
which will be tracked via activemodel, so, dealer.valid?
will return false
(as it's need)?
Upvotes: 0
Views: 210
Reputation: 19879
See the course for valid?
. It first clears any errors, then runs the validations. If you add an error manually it won't see it. Weird, but so says the source. Fix would be to add a validation for keyword_data
so it gets picked up automatically.
def valid?(context = nil)
current_context, self.validation_context = validation_context, context
errors.clear
run_validations!
ensure
self.validation_context = current_context
end
Upvotes: 1