2016-07-22 56 views
0

我試圖用validates_with custom validations helper使用Rails 4混淆validates_with定製驗證語法導軌導示

下面的代碼工作在我的應用程序:

class Photo 
    validates_with CleanValidator 
    include ActiveModel::Validations 
end 

class CleanValidator < ActiveModel::Validator 
    def validate(record) 
    if record.title.include? "foo" 
     record.errors[:title] << "Photo failed! restricted word" 
    end 
    end 
end 

但是我想通過這種幫助多個模型中的多個屬性,而不僅僅是:title

有一個在引導validates_with節包含以下示例的示例:

class GoodnessValidator < ActiveModel::Validator 
    def validate(record) 
    if options[:fields].any?{|field| record.send(field) == "Evil" } 
     record.errors[:base] << "This person is evil" 
    end 
    end 
end 

class Person < ApplicationRecord 
    validates_with GoodnessValidator, fields: [:first_name, :last_name] 
end 

這就是我想要實現的,代有什麼在我的代碼示例,以[:域]爲[標題]我可以將CleanValidator用於多個模型和多個屬性(User.name,Photo.title等)。

回答

1

我想你想從指南,每個驗證程序的另一個例子。你應該可以做

class CleanValidator < ActiveModel::EachValidator 
    def validate_each(record, attribute, value) 
    unless ["Evil", "Other", "Restricted", "Words"].include?(value) 
     record.errors[attribute] << (options[:message] || "is a restricted word") 
    end 
    end 
end 

class Photo 
    include ActiveModel::Validations 
    attr_accessor :title 

    validates :title, clean: true 
end 
+0

這很奇怪,但我已驗證:tag_list,clean:true ..它會阻止照片被創建,如果標籤是「foo」但允許它,如果標籤是「食物「...但是,對於:標題,它會阻止」富「和」食物「。 –