简体   繁体   中英

Custom validations for non persisted model in Rails 4

After have read (almost) all internet I need you input in this problem.

Context: I have a non persisted Rails 4 model using ActiveModel::Model that, according to its documentation, includes ActiveModel::Validations

Code:

class GoodnessValidator < ActiveModel::Validator
  def validate(record)
    if record.first_name == "Evil"
      record.errors[:base] << "This person is evil"
    end
  end
end

class Person
  include ActiveModel::Model
  include ActiveModel::Validations

  validates_with GoodnessValidator
  attr_accessor :first_name
end

Problem: When I'll create a new Person as p = Person.new(first_name: 'Evil') should be validate that is an "evil person". So, I expect an error accessor like p.errors which should return me a Hash with all errors.

But, always is empty, p.errors don't returns nothing. Never.

[102] pry(main)> p = Person.new(first_name: 'Evil')
=> #<Person:0x007fa0925809f0 @first_name="Evil">
[103] pry(main)> p.errors
=> #<ActiveModel::Errors:0x007fa09173ac88 @base=#<Person:0x007fa0925809f0 @errors=#<ActiveModel::Errors:0x007fa09173ac88 ...>, @first_name="Evil">, @messages={}>
[104] pry(main)> p.errors.full_messages
=> []
[105] pry(main)>

The validations are normally triggered when you save the model. In your case, you need to run them manually, then check the errors:

p = Person.new(first_name: 'Evil')
unless p.valid? # runs the validations
  puts inspect p.errors
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM