Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 312
microcosme Avatar asked Jul 10 '12 12:07

microcosme


2 Answers

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
like image 74
Dty Avatar answered Sep 21 '22 12:09

Dty


after_save :update_menu

def updated_menu
  self.class.update_menu
end

this will call the class update_menu method

like image 43
Erez Rabih Avatar answered Sep 22 '22 12:09

Erez Rabih