2012-02-27 116 views
0

我正在构建一个调查应用程序,根据评分我需要某些事情发生。 基本上,如果提交的调查总评分低于15,我们需要通知主管。这对邮件程序来说很简单,但似乎无法通过after_create方法访问评级数据。rails:在after_create中访问成员变量

我的模型有5个字段,分别命名为A,B,C,D和E,它们是整数,它们在表单中包含评级数据。

我已经尝试过:符号我已经尝试过self.notation,我试过after_create(service)service.notation并且没有任何作用 - 电子邮件从未被发送,因为它没有意识到评级低于15。

我也有一个类似问题的复选框。在数据库中它显示为“true”,但在保存之前它通常显示为1,因此测试正确的值是非常棘手的。与下面的代码类似,我也无法访问它的值。我列出了所有我尝试过的各种方法,但都没有成功。

显然,这些都不是在同一时间模型中所有存在的,他们在下面列出的是我已经尝试

如何在after_create电话访问这些数据值的例子?

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 
+1

当你说这是行不通的,会发生什么?如果你在lowScore方法中插入一个断点,你的对象的属性是什么? – 2012-02-27 15:25:32

+0

我明白了,我觉得自己像个白痴。我会发布我的解决方案。 – Oranges13 2012-02-27 15:29:51

回答

1

找出解决方案。

在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 

的关键是使用Proc.new来做为条件测试。

1

待办事项调试:

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