How can I define a custom Mongoid validator for Rails 3?

2,819 views
Skip to first unread message

Kristian Mandrup

unread,
Dec 23, 2010, 6:59:32 AM12/23/10
to Mongoid
I am using Mongoid 2 beta 20 and Rails 3.0.3

class Person
include Mongoid::Document

embeds_one :address, :allow_nil => false
validates_associated :address

before_validation :check_embedded

private

def check_embedded
puts "address: #{self.address.inspect}"
if self.address == nil
puts "adding error"
errors.add(:address, "Address can't be empty")
puts "errors now: #{errors}"
end
end
end

When I run the following spec, the before_validation trigger is
executed and the errors hash populated and then somehow deleted so
that the final error puts prints an empty hash!?

it 'should not create person without an address' do
# lambda { Person.create! first_name: 'Mike', last_name:
'Loehr' }.should raise_error
person = Person.create first_name: 'Mike', last_name: 'Loehr'
puts "errors: #{person.errors}"
end


$ rspec spec/models/person_spec.rb

adding error
errors now: {:address=>["Address can't be empty"]}
errors: {}

Should I use the ActiveModel validate method instead!? Any examples
out there?

Cyril Mougel

unread,
Dec 23, 2010, 7:12:33 AM12/23/10
to mon...@googlegroups.com


The Validation system on Mongoid is the same that ActiveRecord because
use ActiveModel::Validation system.

In the before_validation, the errors.add can't works because its
delete when validation arrive. You just need add your validation with
the key validate :

instead
before_validation :check_embedded

use

validate :check_embedded

--
Cyril Mougel
http://blog.shingara.fr

Vous souhaitez poser des questions sur Ruby ?
N'hésitez pas à aller sur http://questions.rubyfr.org/

Reply all
Reply to author
Forward
0 new messages