简体   繁体   English

Rails将验证放在模块mixin中?

[英]Rails put validation in a module mixin?

Some validations are repetitive in my models: 在我的模型中,一些验证是重复的:

validates :name, :length => { :minimum => 2 }, :presence => true, :uniqueness => true
validates :name_seo, :length => { :minimum => 2 }, :presence => true, :uniqueness => true

How would I put that in a mixin? 我怎么把它放在mixin中? I get this error if I just put 'em in a mixin 如果我把它们放在mixin中,我会收到这个错误

app/models/validations.rb:5: undefined method `validates' for Validations:Module (NoMethodError)
module Validations
  extend ActiveSupport::Concern

  included do
    validates :name, :length => { :minimum => 2 }, :presence => true, :uniqueness => true
    validates :name_seo, :length => { :minimum => 2 }, :presence => true, :uniqueness => true
  end
end

The validates macro must be evaluated in the context of the includer, not of the module (like you probably were doing). 必须在包含器的上下文中评估validates宏,而不是模块的评估(就像你可能正在做的那样)。

Your module should look something like this: 你的模块应该是这样的:

module CommonValidations
  extend ActiveSupport::Concern

  included do
    validates :name, :length => { :minimum => 2 }, :presence => true, :uniqueness => true
    validates :name_seo, :length => { :minimum => 2 }, :presence => true, :uniqueness => true
  end
end

Then in your model: 然后在你的模型中:

class Post < ActiveRecord::Base
  include CommonValidations

  ...
end

I'm using ActiveSupport::Concern here to make the code a little clearer. 我在这里使用ActiveSupport :: Concern使代码更清晰一些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM