簡體   English   中英

如果沒有傳入強參數,我如何更新當前模型中的參數?

[英]How i can update parameter in the current model if it is not passed in strong parameters?

我有帶有 3 個參數(副本、已售副本、剩余副本)的模型銷售,並且我的 SellingsController 如下所示:

def update

  @selling = Selling.find(params[:id])

  @selling.update(selling_params)

  render json: @selling

end



private

def selling_params

  params.require(:selling).permit(:copies, :selled_copies)

end

當我發送帶有 2 個參數(副本和已售副本)的 PATCH 請求時,我想在當前模型中再更新一個參數:剩余副本(其值必須是:副本 – 已售副本)並且我也想將此值寫入數據庫。 你能暗示我如何實現這個嗎?

在您的銷售模式中:

class Selling < ApplicationRecord
  after_update :count_remaining_copies

  def count_remaining_copies
   self.update_columns(remaining_copies: self.copies - self.selled_copies)
  end
end

使用update_columns而不是update ,因此您不會無休止地觸發此回調(堆棧級別太深錯誤)。

我選擇了after_update回調,但您可以使用另一個回調,請參閱: https : after_update

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM