Question

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
Was it helpful?

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.

OTHER TIPS

Do debug:

class Service < ActiveRecord::Base
  after_create :low_score
  def low_score
    # raise (A+B+C+D+E).inspect # uncomment this line to debug your code
    # it will raise exception with string containing (A+B+C+D+E). See what is result this line in your console tab where rails server started
    # Or you can see result in your browser for this raise
    ServiceMailer.toSupervisor(self).deliver if (A+B+C+D+E) < 15
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top