Update Products
Learn how to add the standard HTTP method PUT for the Product model in the API.
We'll cover the following...
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 < ApplicationControllerbefore_action :set_product, only: %i[show update]before_action :check_login, only: %i[create]before_action :check_owner, only: %i[update]# ...def updateif @product.update(product_params)render json: @productelserender json: @product.errors, status: :unprocessable_entityendendprivate# ...def check_ownerhead :forbidden unless @product.user_id == current_user&.idenddef set_product@product = Product.find(params[:id])endend
The implementation is quite simple. We will retrieve the product from the ...