Update Products

Learn how to add the standard HTTP method PUT for the Product model in the API.

Hopefully, by now the logic to build the upcoming actions is clear. This lesson will focus on the update action for when we need to fetch the product from the database and update it.

Define update action

We will implement the update action on the users controller in app/controllers/api/v1/products_controller.rb. The code for the update function is below.

Press + to interact
class Api::V1::ProductsController < ApplicationController
before_action :set_product, only: %i[show update]
before_action :check_login, only: %i[create]
before_action :check_owner, only: %i[update]
# ...
def update
if @product.update(product_params)
render json: @product
else
render json: @product.errors, status: :unprocessable_entity
end
end
private
# ...
def check_owner
head :forbidden unless @product.user_id == current_user&.id
end
def set_product
@product = Product.find(params[:id])
end
end

The implementation is quite simple. We will retrieve the product from the ...