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??
views:
13answers:
1
+1
A:
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
lambdabutz
2010-06-11 19:50:21
@Iambdabutz can i pass parameters with the functions this way ?
krunal shah
2010-06-11 19:56:26
I'm not sure I totally understand your question. You can also pass a block so you instead do: before_validation {|record| some_test_before_validation_method(some_arg) } if you wanted.
lambdabutz
2010-06-11 20:00:10
I have function like def test1(att1,att2) end def test2 end before_validation :test1(att1,att2),:test2 is this work ?
krunal shah
2010-06-11 20:08:48
No, since :test1 and :test2 are symbols. I don't completely remember how the callbacks work, but you might be able to do something like before_validation :test1, att1, att2; before_validation :test2; Either way you could just do before_validation {|record| test1(att1, att2)}; before_validation {|record| test2};
lambdabutz
2010-06-11 20:28:34
Thank you......
krunal shah
2010-06-11 20:30:28