有多種方法可以做到這一點。
你最簡單的解決方案:
def check_depth
self.errors.add(:depth, "Issue with depth") if self.value > 2 # this does not support I18n
end
最乾淨的使用模型驗證(您category.rb的頂部,只需添加):
validates :depth, :inclusion => { :in => [0,1,2] }, :on => :create
如果您的驗證邏輯得到更復雜的,使用自定義驗證程序:
# lib/validators/depth_validator.rb (you might need to create the directory)
class DepthValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add(attribute, "Issue with #{attribute}") if value > 2 # this could evene support I18n
end
end
在使用此驗證程序之前,編輯加載它,例如在初始化
# config/initializers/require_custom_validators.rb
require File.join('validators/depth_validator')
您需要重新啓動您的軌道服務器更改後(和您在您的驗證作出更改之後)。
現在,在您的產品類別型號:
validates :depth, :depth => true, :on => :create # the :on => :create is optional
問題將在@category.save
提高,所以你可以設置你的閃光的通知,像這樣:
if @category.save
# success
else
# set flash information
end
哎呀,如果驗證邏輯不太複雜,你甚至不需要自定義過濾器 - 將更新我的答案。 – emrass 2012-04-15 07:50:10
謝謝你提供的所有信息,我用它提供了最直接的答案,並且確實使用了I18n,所以我將使用自定義驗證器。非常感謝你的努力。 – ruevaughn 2012-04-15 21:39:56
太棒了! I18n也將採用上述「最乾淨」的解決方案(選項2)。您只需在您的語言環境中爲[en | de | ...]。errors.messages.inclusion進行翻譯 - 或者在此處使用示例語言環境之一https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale作爲基礎。對於自定義驗證器,而不是錯誤文本「mytext ...」放置一個符號,如:depth_not_in_range,並在[locale] .collaboration.errors.models.category.attributs.depth.depth_not_in_range中有翻譯 – emrass 2012-04-15 22:09:35