最终创建了一个非常具体的验证器并将其添加到客户端验证中。这是故障
在模型/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'] = function(element, options) { if ($.ajax({ url: '/validators/fund_name_not_company_name', data : { name: element.val() }, // async必须为 false async: false }).status == 404) { return options.message; } }
这帮助很大