Mongoid:如何让 Mongoid 识别我的自定义 ActiveModel 验证?
我有一个模型,其中包含名称数组,我想确保只有一个文档可以具有给定名称。我正在尝试编写一个自定义验证来处理这个问题。我的自定义验证和模型目前看起来像这样:
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
但我收到未知验证器:“unique_names”(ArgumentError)。 Mongoid 文档说每个模型都包含 ActiveModel::Validation,我认为这将允许它们使用我的自定义验证。我还尝试进行从 ActiveModel::Validator 继承的验证并使用 validates_with,但这也不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是 Rails 3,则可能不会自动从 lib 下获取 unique_name_validator.rb,除非您在 application.rb 中添加以下内容:
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:
自定义验证适用于我的 mongoid,但我需要从我的模型文件中要求它:
也许有一种方法可以配置 Rails/mongoid 以自动选取自定义验证器?
The custom validation works for me with mongoid, but I needed to require it from my model file:
Perhaps there is a way to configure rails/mongoid to automatically pick up custom validators?
自动加载 application.rb 中的 lib 文件
config.autoload_paths += %W(#{config.root}/lib)
或将
unique_name_validator.rb
放到initializer< /代码> 文件夹
Either autoload lib file in application.rb
config.autoload_paths += %W(#{config.root}/lib)
Or drop
unique_name_validator.rb
toinitializer
folder为了唯一性,请使用:
validates_uniqueness_of
(来自 http://mongoid.org/docs/validation /)
validates_each
也可以工作。For uniqueness, use:
validates_uniqueness_of
(From http://mongoid.org/docs/validation/)
validates_each
works too.