我正在爲名爲Project的模型中的屬性編寫自定義驗證方法。這裏是我的代碼:rails自定義驗證數組返回未定義的方法錯誤
def self.skill_options
categories = Craft.all.collect{|craft| craft.label} #should change this later
return categories
end
validate :validate_tag_list
def validate_tag_list
puts skill_options.inspect.to_s
puts 'validate tag list is happening'
self.tag_list.each do |tag|
if self.skill_options.include?(tag)
puts tag.to_s + 'is included yo'
else
puts tag.to_s + 'not included yo'
self.errors.add(:tag_list, "#{tag} is not a valid skill.")
end
end
end
出於某種原因,我被告知:
NameError (undefined local variable or method `skill_options' for #<Project:0x007fb6fc02ac28>)
我不知道這是爲什麼。我在同一個模型中爲另一個稱爲category的屬性進行了另一個驗證。這個驗證完美。下面是代碼:
def self.category_options
categories = Craft.all.collect{|craft| craft.label} #should change this later
end
validates :category, inclusion: {in: category_options}
唯一的區別在於,第一驗證(技能)需要一個自定義的驗證,因爲它是一個數組。
我該如何擺脫錯誤?
啊,太好了,謝謝 – Philip7899