30

在我的模型中,一些验证是重复的:

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

我怎么把它放在mixin中?如果我只是将它们放入 mixin 中,我会收到此错误

app/models/validations.rb:5: undefined method `validates' for Validations:Module (NoMethodError)
4

2 回答 2

53
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

必须在包含器的validates上下文中评估宏,而不是在模块的上下文中(就像您可能正在做的那样)。

于 2012-07-07T05:37:52.760 回答
29

您的模块应如下所示:

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

然后在你的模型中:

class Post < ActiveRecord::Base
  include CommonValidations

  ...
end

我在这里使用ActiveSupport::Concern来使代码更清晰一些。

于 2012-07-07T05:38:23.240 回答