2014-09-05 32 views
3

我有一個自定義的驗證方法:傳遞字段名作爲參數傳遞給自定義的驗證方法的Rails 4

def my_custom_validation 
    errors.add(specific_field, "error message") if specific_field.delete_if { |i| i.blank? }.blank? 
end 

的目標是禁止含有[""]穿過驗證參數,但我需要調用此方法,如:

validate :my_custom_validation #and somehow pass here my field names 

例如:

validate :my_custom_validation(:industry) 

回答

5

由於需要到v alidate多個屬性這樣我會建議一個自定義的驗證,像這樣:

class EmptyArrayValidator < ActiveModel::EachValidator 
    def validate_each(record, attribute, value) 
    record.errors[attribute] << (options[:message] || "cannot be emtpy") if value.delete_if(&:blank?).empty? 
    end 
end 

然後驗證爲

validates :industry, empty_array: true 
validates :your_other_attribute, empty_array: true 

或者,如果你不想創建一個特定的類,因爲它是隻需要1模型你可以包括在模型本身

validates_each :industry, :your_other_attribute, :and_one_more do |record, attr, value| 
    record.errors.add(attr, "cannot be emtpy") if value.delete_if(&:blank?).empty? 
end 
相關問題