【问题标题】:Share validations across models with rails 4使用 rails 4 跨模型共享验证
【发布时间】:2014-01-14 09:48:34
【问题描述】:

还有其他问题与此有关,但似乎都是< Rails 4,而且,它们都不是很详细!

他们都在谈论创建一个模块来分享这些常见的验证:

require 'active_record'
module ContactValidations
  def self.included(base_class)
    base_class.class_eval do
      include ContactValidations::InstanceMethods
      # model validations
      validates_presence_of(:name, :message => 'You must provide a company name.')
      validates_presence_of(:street, :message => 'You must provide a company street.')
      validates_presence_of(:city, :message => 'You must provide a company city.')
      validates_presence_of(:post_code, :message => 'You must provide a company post code.')

      validates_numericality_of(:telephone, :on => :create, :message => 'Telephone should be a number with no spaces.', :if => :telephone_given?)    
      validates_numericality_of(:area_code, :on => :create, :message => 'Telephone area code should be a number with no spaces.', :if => :area_code_given?)

      validates_numericality_of(:fax, :on => :create, :message => 'Fax should be a number with no spaces.', :if => :fax_given?)

      validates_numericality_of(:fax_area_code, :on => :create, :message => 'Fax area code should be a number with no spaces.', :if => :fax_area_code_given?)

      validates_format_of(:web, :with => /^((http)?:\/\/)?(www\.)?([a-zA-Z0-9]+)(.[a-zA-Z0-9]{2,3})(\.[a-zA-Z0-9]{2,3})$/, :on => :create, :message => 'Web address is invalid. Example: http://www.domain or http://domain.', :if => :web_given?)

      validates_format_of(:email, :with => /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/, :on => :create, :message => 'Th email address given is invalid.', :if => :email_given?)

      validates_uniqueness_of(:email, :message => 'This email is already given.')
    end
  end

  module InstanceMethods
    def telephone_given?
      !telephone.blank?
    end

    def fax_given?
      !fax.blank?
    end
    def web_given?
      !web.blank?
    end
    def email_given?
      !email.blank?
    end
    def area_code_given?
      !area_code.blank?
    end
    def fax_area_code_given?
      !fax_area_code.blank?
    end

  end
end

但我不知道应该将这样的文件保存在哪里。在 lib 目录中? lib目录下的所有文件都包含在内,对于我只想包含在两个或三个模型中的模块来说似乎有点浪费......

  1. Rails 4 是否具有共享验证的内置方式?
  2. 如果没有,我应该将我的自定义模块保存在哪里?
  3. 为了非常清楚,我应该如何在需要包含这些验证的模型中要求此模块?

【问题讨论】:

    标签: validation ruby-on-rails-4


    【解决方案1】:

    app/models/concerns 中创建模块,然后将它们包含在您的类中:

    include ContactValidations
    

    这样,Rails 将自动加载共享模块并让您可以包含它们。

    【讨论】:

    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多