Search code examples
ruby-on-rails-3observer-pattern

What is preventing this observer before_save from working properly?


I've created an Observer for the User class (below). I know the before_save method is getting called, and I know that the new_record condition is being entered, however the new record is never saved...am I missing something fundamental to the before_save callback?

The save in the controller looks like (the error count produced by the puts is zero):

def create
    @user = User.new(params[:user])
    if @user.save
      #UserMailer.registration_confirmation(@user).deliver
      redirect_to root_url, :notice=>"Signed Up!"
    else
      puts @user.errors.count
      render "new"
    end
  end

class UserObserver < ActiveRecord::Observer
  observe :user

  def before_save(user)
    if user.new_record?
      puts 'HELLLLLLLLLLP'
      #todo make a confirmation code generator
      user.confirmationcode='1234'
      user.confirmed=false
    else
      if user.email_changed?
        user.confirmationcode='123'
        user.confirmed=false
      end
    end
  end

  def after_save(user)
    if user.confirmed=false
      UserMailer.confirm_registration(user).deliver
    end
  end

end

Solution

  • In Ruby, the result of the last line of a method or block is used as its return value, and a before_save hook can cancel the save action by returning false. If you look, the last line of your if user.new_record? branch is going to return false. Make sure your before_save is returning something that evaluates to true, and you'll be good.