dadads
dadads

Reputation: 201

Rails: Should I use observers or callbacks (to keep fields up to date)?

I am developing a system where ActiveRecord entities and fields need to be kept consistent at all times. Quite often, certain fields are derived from other fields and need to be kept up to date at all times. Sometimes, this may even happen across entities.

For example:

class User < ActiveRecord::Base
  attr_accessible :first_name, :last_name
  attr_protected  :name

  # I need to keep 'name' up to date at all times
  after_update do
    name = self.first_name + ' ' + self.last_name
    true
  end
end

The philosophical question here is whether or not I should implement this type of behaviour (and hundreds of similar ones) in a callback or inside an observer. I can think of a few reasons to do both below:

Callbacks

Observers

Can someone with more experience please enlighten me?

Upvotes: 2

Views: 1797

Answers (1)

gylaz
gylaz

Reputation: 13581

According to Design Patterns book this is most appropriate for the Observer pattern. With and Observer, your after_update/save logic is decoupled from your model. Hard to tell from your example, but if you are updating other models from your callbacks then you are polluting your User model with knowledge of other model. Thus, and Observer should step in to take care of that.

Also, you can disable observers in Rails, thus making your unit tests faster where you don't care about "callbacks" getting triggered.

Upvotes: 1

Related Questions