2010-06-11 62 views
0
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

您可以設置多個方法來由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

+0

@Iambdabutz我可以傳遞參數與功能的這種方式? – 2010-06-11 19:56:26

+0

我不確定我完全理解你的問題。您也可以傳遞一個塊,然後執行:before_validation {| record | some_test_before_validation_method(some_arg)}如果你想。 – lambdabutz 2010-06-11 20:00:10

+0

我有這樣 高清測試1(ATT1,ATT2) 結束 高清test2的 結束 before_validation功能:TEST1(ATT1,ATT2),: TEST2 是這項工作? – 2010-06-11 20:08:48