简体   繁体   English

如果没有传入强参数,我如何更新当前模型中的参数?

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

I have model Selling with 3 parameters (copies, selled_copies, remaining_copies) and i have SellingsController looks like this:我有带有 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

When i send PATCH request with 2 parameters (copies and selled_copies) i want to update one more parameter in the current model: remaining_copies (the value of this must be: copies – selled_copies) and i want to write this value in db too.当我发送带有 2 个参数(副本和已售副本)的 PATCH 请求时,我想在当前模型中再更新一个参数:剩余副本(其值必须是:副本 – 已售副本)并且我也想将此值写入数据库。 May you hint how i can implement this?你能暗示我如何实现这个吗?

In your selling model:在您的销售模式中:

class Selling < ApplicationRecord
  after_update :count_remaining_copies

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

Use update_columns instead of update , so you don't trigger this callback endlessly ( stack level too deep error ).使用update_columns而不是update ,因此您不会无休止地触发此回调(堆栈级别太深错误)。

I chosed the after_update callback but you could use another, please see: https://guides.rubyonrails.org/active_record_callbacks.html我选择了after_update回调,但您可以使用另一个回调,请参阅: https : after_update

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM