0

I have

class Users < ActiveRecord::Base
  belongs_to :team, touch: true
end

class Team < ActiveRecord::Base
  has_many :users
  before_save :update_popularity
  before_update :update_popularity

  def popularity
    #secret algorythm
  end

private
  def update_popularity
    # This is not called
  end
end


User.first.name = 'John'

When I save a user I would like to update the team popularity as well. However the before_filter doesn't seem to be invoked?

Is there any proper way for doing this?

Boti
  • 3,275
  • 1
  • 29
  • 54
  • Maybe this helps? http://stackoverflow.com/questions/2231415/does-activerecord-save-a-belongs-to-association-when-saving-main-object – shadowhorst Feb 21 '14 at 09:59
  • I tried the callback is still not called. – Boti Feb 21 '14 at 10:07
  • What about calling the models before_save or after_save callback, find the associated team within the method and call its update_popularity? – shadowhorst Feb 21 '14 at 10:09
  • @shadowhorst That is what I tried to avoid... To manually call that method from the child... – Boti Feb 21 '14 at 10:11
  • 1
    I've never seen before_filter used in a model before: usually it's for controllers, and in the model you have before_save, before_create etc. Is this a new addition to rails? – Max Williams Feb 21 '14 at 10:37
  • @MaxWilliams Sorry... I misspelled the hooks... The are corrected now. – Boti Feb 22 '14 at 11:19
  • Finnally I put an after_save in the child model and called the hook in the parrent manually from the childs after_save hook. – Boti Feb 22 '14 at 11:20

1 Answers1

1

Try this before_update :update_popularity

Update:

After reviewing the API doc of touch method here, they say:

Please note that no validation is performed and only the after_touch callback is executed.

Zakwan
  • 1,072
  • 2
  • 11
  • 22