当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - 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, :unique_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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: