Reputation: 2720
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)>
Upvotes: 1
Views: 153
Reputation: 18193
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
Upvotes: 2