Rails:After_Createのメンバー変数へのアクセス
-
13-11-2019 - |
質問
私は評価に基づいている調査アプリを構築しています。 基本的に、調査が15歳未満の合計評価で送信された場合は、スーパーバイザーに通知する必要があります。それはメーラと十分に簡単ですが、After_Createメソッドの格付けデータにアクセスすることはできません。
マイモデルには、整数であるA、B、C、D、Eという名前の5つのフィールドがあり、定格データをフォームに保持しています。
私は試してみました:私は自己を試したことがありました、私はafter_create(サービス)サービスを試しました、そして何も機能しませんでした - それは評価が15より低いことを認識しないので送信されません。
私は同様の問題を持つチェックボックスを持っています。データベースでは「true」として表示されますが、保存される前に通常表示されます。通常、正しい値のテストは難しいです。以下のコードと同様に、それはその値にアクセスできない。私は成功せずに試したさまざまな方法をすべてリストしました。
明らかにこれらはすべてモデルに同時に存在するわけではありませんが、私が試みたものの例として以下にリストされています
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
解決
は解を図形化した。
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を使用して条件のテストを行っていました。
他のヒント
デバッグ:
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
.