0

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)?

Alex Antonov
  • 14,134
  • 7
  • 65
  • 142

1 Answers1

1

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

https://github.com/rails/rails/blob/107f4282bbfabc011d5ad3bcf3fb3c6fb812ad30/activemodel/lib/active_model/validations.rb#L334

Philip Hallstrom
  • 19,673
  • 2
  • 42
  • 46
  • Can you explain me how to write this validation, please? – Alex Antonov Nov 13 '15 at 18:44
  • @asiniy not without knowing what that validation should be (which your code doesn't indicate) – Philip Hallstrom Nov 13 '15 at 18:45
  • Updated my `Dealer` class – Alex Antonov Nov 13 '15 at 18:48
  • @PhilipHallstrom The source you showed above is from ActiveModel. `valid?` method in ActiveRecord is a bit different https://github.com/rails/rails/blob/59190c037999d302dd95b1f53f7049c2cec3f7b9/activerecord/lib/active_record/validations.rb#L56 . There is no `clear` process here. Can you explain that? – Van Huy Nov 13 '15 at 19:02
  • Interesting. Missed that, but still, this version calls `super` which I would hazard a guess (didn't check) calls the above which calls clear. – Philip Hallstrom Nov 13 '15 at 19:04
  • Ah, I see. It has `include ActiveModel::Validations` https://github.com/rails/rails/blob/59190c037999d302dd95b1f53f7049c2cec3f7b9/activerecord/lib/active_record/validations.rb#L31 – Van Huy Nov 13 '15 at 19:15