Rails 将验证放入模块 mixin 中? [英] Rails put validation in a module mixin?

查看:14
本文介绍了Rails 将验证放入模块 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

我如何将它放入 mixin 中?如果我只是把它们放在一个 mixin 中,我就会得到这个错误

How would I put that in a mixin? I get this error if I just put 'em in a 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

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

The validates macro must be evaluated in the context of the includer, not of the module (like you probably were doing).

这篇关于Rails 将验证放入模块 mixin 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆