如何验证列可以更新一次?

时间:2019-01-19 10:23:28

标签: ruby-on-rails validation ruby-on-rails-5

我有一个协议模型,它有一个released_at列。我想确认协议可以一次发布。我该怎么做?

控制器:

 # GET /aggreements/1/release
 def release
   @agreement.update(released_at: Time.now.utc)

   if @agreement.save
     render json: {success: ["Agreement released."]}
   else
     render json: @agreement.errors, status: :unprocessable_entity
   end
 end    

型号:

class Agreement < ApplicationRecord
  validate :released_agreement_cannot_be_released

  def released_agreement_cannot_be_released
    if released_at.present?
      errors.add(:released_at, "already released")
    end
  end
end

谢谢。

1 个答案:

答案 0 :(得分:0)

我知道了,这是解决方案。

控制器:

 # GET /agreements/1/release
 def release
   @agreement.released_at = Time.now.utc

   if @agreement.save
     render json: {success: ["Agreement released."]}
   else
     render json: @agreement.errors, status: :unprocessable_entity
   end
 end    

型号:

class Agreement < ApplicationRecord
  validate :released_agreement_cannot_be_released

  def released_agreement_cannot_be_released
    if released_at_was.present?
      errors.add(:released_at, "already released")
    end
  end
end