سؤال

I am trying to send an email from my app. The email gets sent when I don't use observer. When I use observer i get the following error :

undefined local variable or method ` UserMailer' for #<UserObserver:0x7f5730c07400>

Here's my UserMailer

class UserMailer < ActionMailer::Base
  default :from => "from@me.com"    
  def welcome_email(user)
    @user = user
    @url  = "website.com/home"
    mail(:to => user.email, :subject => "Welcome to My Awesome Site")
  end
end

The observer code

require "#{Rails.root}/app/mailers/user_mailer.rb" 

class UserObserver < ActiveRecord::Observer
    observe :user

  def after_save(user)
     UserMailer.welcome_email(user).deliver
  end

end

Any help will be appreciated. I am a nuby to ruby on rails. TIA

هل كانت مفيدة؟

المحلول

Observers have been removed in rails 4.
Which means, even though you can still use them with a gem, they are a deprecated and you should not use them.

The main reason for it is that observers are making your application a mess to read for new developers.

I would suggest you to use services (take a look at this post, which mentions how you can refactor your AR models properly), and send your email in one of them.

نصائح أخرى

Do you have the below line setup in your application.rb file?

config.active_record.observers = :user_observer

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top