结束创建一个非常具体的验证器并将其添加到客户端验证。 Here'z在配置/初始化/验证击穿
在模型/ fund.rb
validates_fund_name_not_company_name :name
新的文件名为.. 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 /资产/ JavaScript的/rails.validations.custom.js clientSideValidations.validators.remote ['fund_name_not_company_name'] = function(element,options)if($ .ajax({/ validators/fund_name_not_company _name', data:{name:element.val()}, // async must be false async:false })。status == 404){return options.message; }}
This了大量帮助
的感谢!你的文章帮了我很多! – alt 2013-05-23 10:26:35