Mongoid: How can I make Mongoid recognize my custom ActiveModel validations?
I have a model, which has and array of names and I want to ensure that only one document can have a given name. I'm trying to write a custom validation to handle this. My custom validation and the model look like this at the moment:
lib/unique_name_validator.rb
class UniqueNamesValidator < ActiveModel::EachValidator
def validate_each( record, attribute, value )
end
end
app/models/MyModel.rb
class MyModel
include Mongoid::Document
validates :names, :un开发者_如何学编程ique_names => true
field :names, :type => Array
end
But I'm getting Unknown validator: 'unique_names' (ArgumentError). The Mongoid documentation says that each model includes ActiveModel::Validation, which I thought would allow them to work with my custom validations. I've also tried making validation that inherits from ActiveModel::Validator and using validates_with, but that doesn't work either.
If you're using Rails 3, your unique_name_validator.rb may not be picked up from under lib automatically unless you add the following in application.rb:
config.autoload_paths += %W(#{config.root}/lib)
The custom validation works for me with mongoid, but I needed to require it from my model file:
require 'unique_name_validator'
Perhaps there is a way to configure rails/mongoid to automatically pick up custom validators?
Either autoload lib file in application.rb
config.autoload_paths += %W(#{config.root}/lib)
Or drop unique_name_validator.rb
to initializer
folder
For uniqueness, use:
validates_uniqueness_of
(From http://mongoid.org/docs/validation/)
validates_each
works too.
精彩评论