开发者

Use super with before_validation

开发者 https://www.devze.com 2023-01-03 08:57 出处:网络
I have this code in my every model. Class people def before_validation @attributes.each do |key,value|
 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??


You can setup multiple methods to be called by the before_validation callback. So instead of straight up defining the before_validation, you can pass the methods you want to get called 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

You can read more about callbacks here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

0

精彩评论

暂无评论...
验证码 换一张
取 消