ruby-on-railsmodelafter-create

rails: Accessing member variables in after_create


I am building a survey app where, based on ratings I need certain things to happen. Basically, if a survey is submitted with a total rating under 15, we need to notify a supervisor. That's easy enough with mailers, but I can't seem to access the rating data in an after_create method.

My model has 5 fields named A,B,C,D, and E which are integers and they hold the rating data in the form.

I have tried :notation I have tried self.notation, I've tried after_create(service) service.notation and nothing works - the email never gets sent because it doesn't realize that the rating is lower than 15.

I also have a checkbox with similar issues. In the database it appears as "true" but before it is saved it usually shows up as 1 so testing for the correct value is tricky. Similar to the code below, I can't access it's value either. I've listed all the various methods I've tried with no success.

Obviously these are not all existent in the model at the same time, they are listed below as examples of what I have attempted

How do I access these data values in an after_create call?!

class Service < ActiveRecord::Base
  after_create :lowScore

  def lowScore
    if(A+B+C+D+E) < 15 #does not work
      ServiceMailer.toSupervisor(self).deliver
    end
  end

  def lowScore
    if(self.A+self.B+self.C+self.D+self.E) < 15 #does not work either
      ServiceMailer.toSupervisor(self).deliver
    end
  end

  #this does not work either!
  def after_create(service)
    if service.contactMe == :true || service.contactMe == 1
      ServiceMailer.contactAlert(service).deliver
    end
    if (service.A + service.B + service.C + service.D + service.E) < 15
      ServiceMailer.toSupervisor(service).deliver
      ServiceMailer.adminAlert(service).deliver
    end
  end

Solution

  • Figured out a solution.

    In model.rb:

      after_create :contactAlert, :if => Proc.new {self.contactMe?}
      after_create :lowScore, :if => Proc.new {[self.A, self.B, self.C, self.D, self.E].sum < 15}
    
      def contactAlert
        ServiceMailer.contactAlert(self).deliver
      end
    
      def lowScore
        ServiceMailer.adminAlert(self).deliver
        ServiceMailer.toSupervisor(self).deliver
      end
    

    The key was using the Proc.new to do the tests for conditions.