microcosme
microcosme

Reputation: 703

Call a class method in an after_save

That is may be a stupid point, but I don't find the solution.

I have a simple model with a class method update_menu and I want that it is called after each save of instance.

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 to get the after_filter call update_menu?

I tried:

after_save :update_menu

But it looks for the method on the instance (which does not exist) and not on the class.

Thanks for your answers.

Upvotes: 7

Views: 6118

Answers (3)

jpgeek
jpgeek

Reputation: 5281

after_save 'self.class.update_menu'

Rails will evaluate a symbol as an instance method. In order to call a class method, you have to pass a string which will be evaluated in the correct context.

NOTE: This only works with rails 4. See Erez answer for Rails 5.

Upvotes: 5

Erez Rabih
Erez Rabih

Reputation: 15788

after_save :update_menu

def updated_menu
  self.class.update_menu
end

this will call the class update_menu method

Upvotes: 7

Dty
Dty

Reputation: 12273

Make it an instance method by removing self.

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

It doesn't make much sense to have an after_save callback on a class method. Classes aren't saved, instances are. For example:

# 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

Upvotes: 6

Related Questions