before_validation仅触发一个特定列

时间:2011-07-25 14:08:55

标签: ruby-on-rails-3 validation gem

我正在试图弄清楚如何仅触发一个特定列的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”的宝石“在现场”编辑列值

1 个答案:

答案 0 :(得分: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