Search⌘ K

Update Products

Explore how to create an update action for user-owned products in a Rails API. Understand fetching, updating, and securing products with before_action filters. Learn to write tests ensuring only authorized users can update their products and configure routes for PUT and PATCH requests.

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.

Ruby
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 ...