I have model Selling with 3 parameters (copies, selled_copies, remaining_copies) and i have SellingsController looks like this:
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. 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 ).
I chosed the after_update
callback but you could use another, please see: https://guides.rubyonrails.org/active_record_callbacks.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.