Rails Coach

ActiveRecord Observers


Listen Later

About a month ago, I talked about ActiveRecord Callbacks. Observers are a way of moving callbacks out of the Model. Usually this is done to adhere to the Single Responsibility principle. So, for example, programmers will move sending an email when a record is updated or created to an Observer.
class UserObserver < ActiveRecord::Observer
def after_create(user)
UserMailer.sign_up(user).deliver
end
end
 
Observers should be included in your app/models folder and named using the same convention as your models. So in this case, this observer would be saved to /app/models/user_observer.rb.
To load the observer in your application, you need to include this line in your config/application.rb
config.active_record.observers = :user_observer
 
Finally, you can observe more than one model with the same observer.
class SignUpObserver < ActiveRecord::Observer
observer :user, :admin
def after_create(user)
UserMailer.sign_up(user).deliver
end
end
 
I personally like Observers when they help keep you from repeating code or increase code readability. In many cases, I simply keep callbacks in models and violate the Single Responsibility Principle.
...more
View all episodesView all episodes
Download on the App Store

Rails CoachBy Charles Max Wood

  • 4.7
  • 4.7
  • 4.7
  • 4.7
  • 4.7

4.7

3 ratings


More shows like Rails Coach

View all
Teach Me To Code » Screencasts by Charles Max Wood

Teach Me To Code » Screencasts

11 Listeners

JavaScript Jabber by Charles M Wood

JavaScript Jabber

234 Listeners

iPhreaks by Charles M Wood

iPhreaks

17 Listeners

Ruby Rogues by Charles M Wood

Ruby Rogues

45 Listeners

The Freelancers' Show by Charles M Wood

The Freelancers' Show

23 Listeners

React Native Radio by Jamon Holmgren, Robin Heinze, Mazen Chami

React Native Radio

59 Listeners

My JavaScript Story by Charles M Wood

My JavaScript Story

4 Listeners

JavaScript Jabber by Charles M Wood

JavaScript Jabber

62 Listeners

Ruby Rogues by Charles M Wood

Ruby Rogues

21 Listeners

Adventures in Angular by Charles M Wood

Adventures in Angular

15 Listeners