ADV
ADV

Reputation: 97

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:

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?

Upvotes: 0

Views: 505

Answers (1)

Luskmo
Luskmo

Reputation: 341

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

Upvotes: 2

Related Questions