使用super with before_validation

时间:2010-06-11 19:42:39

标签: ruby-on-rails ruby

 I have this code in my every model.
 Class people
   def before_validation
    @attributes.each do |key,value|
      self[key] = nil if value.blank?
    end
   end
 end

 Now i want to put my loop in separate module. Like
 Module test
   def before_validation
     @attributes.each do |key,value|
      self[key] = nil if value.blank?
     end
   end
 end

 And i want to call this before_validation this way
 Class people
   include test
   def before_validation
     super
     .....Here is my other logic part..... 
   end
 end

 Are there any way to do it like that in rails??

1 个答案:

答案 0 :(得分:1)

您可以设置由before_validation回调调用的多个方法。因此,您可以在验证之前传递要调用的方法,而不是直接定义before_validation。

module Test
  def some_test_before_validaiton_method
    # do something
  end
end

class People < ActiveRecord::Base
  include Test
  def people_before_validation_foo
    #do something else
  end
  before_validation :some_test_before_validation_method
  before_validation :people_before_validaiton_foo
end

您可以在此处详细了解回调:http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html