2011-07-25 26 views
1

我想弄清楚如何觸發只有一個特定列的before_validation,如下所示。before_validation只觸發一個特定列

class PartType < ActiveRecord::Base 
    before_validation :fix_quotation 

    protected 
    def fix_quotation 
     self[:quotation] = quotation_before_type_cast.tr(' $, ' , '.') if attribute_names().include?("quotation") 
    end 
end 

但在這種情況下attribute_names似乎不起作用。

我在這個模型上有一些其他列,如果我在其他列做任何改變這個驗證觸發。

此驗證工作正常的「報價單」列,但我不希望在修改審定觸發「,例如標題欄

注:我使用的是被稱爲寶石‘on_the_spot’來「當場」

回答

2

這是你的模型應該如何定義編輯列值:!

class PartType < ActiveRecord::Base 
    before_validation :fix_quotation, :if => :quotation_changed? #this is where the magic happens 

    protected 
    def fix_quotation 
    self[:quotation] = quotation_before_type_cast.tr(' $, ' , '.') if attribute_names().include?("quotation") 
    end 
end 
+0

就像一個魅力等簡單的工作MUITO obrigado,毛裏西奧:-) –