【问题标题】:rails 3 validations uniqueness on attributes of an associationrails 3验证关联属性的唯一性
【发布时间】:2013-03-19 09:19:31
【问题描述】:

我有一个名为 Fund 的模型和一个名为 Company .. 的模型,其中基金属于一家公司。

我的基金表中有此验证:

validates :name, presence: true, uniqueness: true

这在服务器端和客户端都可以使用client_side_validations。但我希望我的基金名称在 fund.name 值和 fund.company.name 值中都是唯一的。我也想以一种与client_side_validations 一起使用的方式来做这件事。

建议?

【问题讨论】:

    标签: ruby-on-rails-3 validation client-side-validation validates-uniqueness-of


    【解决方案1】:

    最终创建了一个非常具体的验证器并将其添加到客户端验证中。这是细分

    在models/fund.rb中

    validates_fund_name_not_company_name :name
    

    config/initializers/validators .. 中的新文件名为 fund_name_not_company_name_validator.rb

    class FundNameNotCompanyNameValidator < ActiveModel::EachValidator
      def validate_each(record, attr_name, value)
        if ::Company.exists?(name: value)
          record.errors.add(attr_name, :fund_name_not_company_name, options.merge(:value => value))
        end
      end
    end
    
    # This allows us to assign the validator in the model
    module ActiveModel::Validations::HelperMethods
      def validates_fund_name_not_company_name(*attr_names)
        validates_with FundNameNotCompanyNameValidator, _merge_attributes(attr_names)
      end
    end
    
    module ClientSideValidations::Middleware
      class FundNameNotCompanyName < ClientSideValidations::Middleware::Base
        def response
          if ::Company.exists?(name: request.params[:name])
            self.status = 404
          else
            self.status = 200
          end
          super
        end
      end
    end
    

    然后在 app/assets/javascripts/rails.validations.custom.js clientSideValidations.validators.remote['fund_name_not_company_name'] = 函数(元素,选项){ 如果 ($.ajax({ url: '/validators/fund_name_not_company_name', 数据:{名称:element.val()}, // 异步必须为假 异步:假 }).status == 404) { return options.message; } }

    This 帮了大忙

    【讨论】:

      猜你喜欢
      • 2011-03-17
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多