前提・実現したいこと
ある条件でループを回して、全ての条件でレコードを取得することができたら
そのレコードのカラムをアップデート。できなかかったら、バリでショーンエラーを返す書き方を教えていただきたいです。
該当のソースコード・試したこと
やりたいことを伝えるための雰囲気でのコードになりますが、以下のようなイメージです。
ruby
1def Workflow < ApplicationRecord 2 3 before_save -> { update_accident_progress('payment') } 4 5 def update_progress(status) 6 return if number.blank? # numberがなければリターン 7 8 wf = Workflow.where(number: number) 9 wf.each do |w| 10 as = [] 11 as = Status.find_by( compensation: wf.compensation, progress: status) #statusは引数で受け取っています。 12 end 13 14 if as.all? 15 wf.update_all(progress: status) # 1つでもasにfalseがあれば、update_allは実行したくありません。 16 else 17 errors[:base] << 'ダメです。' 18 end 19 end 20end
補足情報(FW/ツールのバージョンなど)
・Rails 5.1.7
・Ruby 2.6.3
追記
ruby
1StatusはCSVファイルをnewしてモデルのように扱っています。 2class Status 3 attr_accessor :compensation :progress, :status 4 5 def self.find_by(compensation:, progress:) 6 STATUS_MANAGER.find_by(compensation: compensation, progress: progress) 7 end 8 9 def self.statuses 10 STATUS_MANAGER.statuses 11 end 12end 13
追記2
ruby
1module ProgressUpdateble 2 extend ActiveSupport::Concern 3 4 included do 5 after_create -> { update_progress('payment') } 6 validate :check_combination_status 7 end 8 9 def update_progress(status) 10 return if number.blank? 11 w = Workflow.where(approval_status: 'pending', number: number) 12 w.update_all(progress: status) 13 end 14 15 def check_combination_status 16 return if number.blank? 17 wf = Workflow.where(number: number) 18 unless wf.all? { |w| Status.find_by(compensation: w.compensation progress: progress).present? } 19 errors[:base] << 'エラーメッセージ' 20 end 21 end 22end 23
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/07/30 04:56
2019/07/30 04:56
2019/07/30 05:03
2019/07/30 05:13
2019/07/30 05:18
2019/07/30 05:21