我的模型中有些验证是重复的:
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)
答案 0 :(得分:47)
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
宏必须在包含器的上下文中进行评估,而不是模块的评估(就像你可能正在做的那样)。
答案 1 :(得分:26)
您的模块应如下所示:
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来使代码更清晰。