Alex Antonov
Alex Antonov

Reputation: 15156

Rails thinks model with attr_accessor is valid but it doesn't

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

Answers (1)

Philip Hallstrom
Philip Hallstrom

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

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

Upvotes: 1

Related Questions