---
description: General Setup & Layout
---

# :update

<details>

<summary>Notes</summary>

1. **Find the Item**: The `find_item` method, invoked through a `before_action`, retrieves the item based on the passed ID. If it's not found, a `not_found` status (HTTP 404 -- @Jase/STeven) is sent.
2. **Permission Check**: One common task in an update action is to verify if the user (and/or their associated company/organization) has the permission to modify the resource. If not, a `forbidden` status (HTTP 403 -- @Jase/Steven) is returned.
3. **Business Logic Checks**: Sometimes, you might want to prevent updates based on specific business rules. For instance, you might not want to allow updates if an item has reached a particular state or if it's being used elsewhere.
4. **Rails "Concerns" - Update Logic**: If there's common logic associated with updating certain attributes or logging changes, this can be abstracted into a concern.
5. **Update and Response**: We then attempt to update the item using the permitted parameters. If the update is successful, the updated item data is sent back to the client. If there are validation errors, an `unprocessable_entity` status (HTTP 422 -- @Jase/Steven) is sent with the errors.
6. **Strong Parameters**: Just like in the `create` action, the `item_params` method leverages Rails' Strong Parameters to ensure data safety.

</details>

## Example Setup:

```ruby
class ItemsController < ApplicationController
  before_action :find_item, only: [:show, :update, :destroy]

  def update
    # LOCAL HANDLING
    ##################

    # Check if the item belongs to the current company (or another ownership/permission logic)
    unless @item.company == get_current_company
      return render json: { error: 'Not authorized' }, status: :forbidden
    end

    # Additional business logic checks, if needed
    # For instance: is the item currently checked out, or has it reached a certain status?
    # ...

    
    # ABSTRACTED/REUSABLE HANDLING (e.g. Concerns, etc.)
    ##################

    # CONCERNS
    # Maybe there's a concern for updating certain attributes or logging changes?
    # @item = handle_update_logic(@item)

    # OTHER (?)
    # ...    
    
    
    # EXECUTE & RESPOND
    ##################

    # Update the item and render response
    if @item.update(item_params)
      render json: @item
    else
      render json: @item.errors, status: :unprocessable_entity
    end
  end

  # ... Other actions ...

  private

  def item_params
    params.require(:item).permit(:name, :description, :price, ...other permitted attributes...)
  end

  def find_item
    @item = Item.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    render json: { error: 'Item not found' }, status: :not_found
  end
  
end

```
