Niyanta
Niyanta

Reputation: 473

Association Callback Rails

I understand the concept of normal callbacks and association callbacks, i.e when to use which. What I'm puzzled with is what're the possible reasons to prefer normal ones over association callbacks ? I've recently been presented with a situation where I have to go with the former, I want to know why. Are there any performance issues with association callbacks ? I was using after_add in a has_many relationship, to which now I'll be using after_update. Thanks.

Upvotes: 1

Views: 437

Answers (1)

Niyanta
Niyanta

Reputation: 473

I have found out the reason. When you define an action via Association callbacks, they're only triggered when the object is modified using them. For ex, if I have 2 models, User and UserRating, with a relationship like ,

class User
  has_many :user_ratings
end

and I have defined

has_many :user_ratings, after_add :do_something

This will only be triggered if I follow the object creation path,

user.user_ratings.create()

But if I simply try a,

UserRating.create

the callback won't be triggered. Same goes for other association callbacks.

Upvotes: 1

Related Questions