Reputation: 15491
Very simple question but was unable to figure this out. Is it possible to do like:
after_create :log_activity(my_var)
So I could write 1 method that handles all the actions ( destroy,save,update)?
Upvotes: 3
Views: 3407
Reputation: 6247
I'm not sure if this is new in Rails 4.2 vs. when you asked the question was asked, but this works:
after_create -> { log_activity(my_var) }
I wonder if the question you're really getting at is about the scope of my_var
. What is your intention with my_var?
Upvotes: 1
Reputation: 131
You can do something like that:
after_create Proc.new{ log_activity(my_var) }
def log_activity(my_var)
:
end
Upvotes: 1
Reputation: 753
If I right understand you than in my practice was case to update user's balance on create or destroy salary. so try this code:
class Salary < ActiveRecord::Base
after_create { |action| action.update_user_balance(1) }
before_destroy { |action| action.update_user_balance(-1) }
def update_user_balance(val) #val can be +1/-1
user = self.user
user.update(balance: user.balance + self.sum * val)
end
Hope this will help you! :)
Upvotes: 0
Reputation: 2857
No, it is not possible to pass variables to callback method. Reason is simple as callback methods are called by rails stack and when it will call callback method, it did't know what to pass in callback method.
Upvotes: 5