【问题标题】:complex validation on object update?对象更新的复杂验证?
【发布时间】:2015-12-31 07:02:49
【问题描述】:

我有一个模型“WorkDetail”,与问题相关的 db-attrs 是“name”、“status”和“approved_status”,数据类型均为整数,模型类定义如下:-

class WorkDetail < ActiveRecord::Base
  enum name: [:smartcheck, :install, :verify]
  enum status: [:pending, :inprogress, :complete]

  belongs_to :work_order
  has_many :cabinets

  after_save :work_order_status_update

  private

  def work_order_status_update
    work_detail_count = self.work_order.work_details.count
    status_array = self.work_order.work_details.where(status: 2).count
    if status_array == work_detail_count
      if work_detail_count == 0
        self.work_order.update({status: "pending"})
      else
        self.work_order.update({status: "complete"})
      end
    else
      self.work_order.update({status: "inprogress"})
    end
  end
end  

现在,我想添加自定义验证以应用于以下问题:-

  1. 验证应该只适用于更新过程。

  2. 如果对象的 name == "smartcheck"status == "complete" 则只有 approved_status 布尔属性应该是 updatedtrue( 迁移时默认为 false),否则应给出错误 smartchecked 并且尝试更新时状态未完成 批准状态属性。

希望这个问题有意义,谢谢!!!提前,伙计们,快乐编码。

【问题讨论】:

    标签: ruby activerecord ruby-on-rails-4.1 mysql2


    【解决方案1】:

    1) 验证仅适用于更新过程

     after_save :work_order_status_update,  :on => :update
    

    2) 如果对象的名称 == "smartcheck" 和状态 == "完成" 那么只有 已批准的状态布尔属性应更新为真( 迁移时默认为 false),否则应给出错误 smartchecked 并且尝试更新时状态未完成 批准状态属性。

    def test_status_and_name
      if self.name == "smartcheck" and self.status == "complete"
        self.update_attributes(approved_status: true)
      else
        errors[:base] << "smartchecked and the status is not complete on trying to update approved_status attr."
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 2023-03-13
      • 2014-11-12
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多