Class method call in after_save

This may be a dumb point, but I can’t find a solution.

I have a simple model with an update_menu class method, and I want it to be called after every instance is saved.

 Class Category attr_accessible :name, :content def self.menu @@menu ||= update_menu end def self.update_menu @@menu = Category.all end end 

So what is the correct syntax for calling after_filter update_menu ?

I tried:

 after_save :update_menu 

But he is looking for the method in the instance (which does not exist), and not in the class.

Thank you for your responses.

+6
source share
3 answers

Make it an instance method by removing self .

 # now an instance method def update_menu @@menu = Category.all end 

It doesn't make sense to have an after_save for a class method. Classes are not saved, instances. For instance:

 # I'm assuming the code you typed in has typos since # it should inherit from ActiveRecord::Base class Category < ActiveRecord::Base attr_accessible :name end category_one = Category.new(:name => 'category one') category_one.save # saving an instance Category.save # this wont work 
+6
source
 after_save :update_menu def updated_menu self.class.update_menu end 

this will call the class method update_menu

+6
source
 after_save 'self.class.update_menu' 

Rails will evaluate the symbol as an instance method. To call a class method, you must pass a string that will be evaluated in the correct context.

NOTE. This only works with rails 4. See Erez's answer to rails 5.

+4
source

Source: https://habr.com/ru/post/920119/


All Articles