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

# :create

<details>

<summary>Notes</summary>

1. **New Instance Creation**: We start by creating a new instance of the `Item` model using the parameters that are permitted. This ensures that we only take in the data that our system expects and can handle safely.
2. **Association with Company**: The newly created item is associated with the currently active company. This association is essential to ensure that the item belongs to the right segment or organization.
3. **User Association**: If we're tracking which user created an item, we associate the item with the currently logged-in user.
4. **Rails "Concerns" - Attachments Handling**: In some cases, items might have attachments, images, or files associated with them. Using Rails "Concerns", we can modularize the logic for handling these attachments.
5. **Saving and Response**: After setting up the item, we attempt to save it to the database. If the save is successful, a `created` status (HTTP 201 -- TBD @Jase/Steven) along with the item data is sent back to the client. If there are errors (like validation issues), an `unprocessable_entity` status (HTTP 422 -- TBD @Jase/Steven) is sent with the errors.
6. **Strong Parameters**: The `item_params` method is a private method that leverages Rails' Strong Parameters feature. It ensures that only the parameters we explicitly permit are used to create or update an item, providing an additional security layer against unwanted or malicious data.

</details>

## Example Setup:

```ruby
class ItemsController < ApplicationController
  include QueryParamsProcessor

  def create
    # LOCAL HANDLING
    ##################
    
    # Create a new item instance with permitted parameters
    @item = Item.new(item_params)

    # Associate the item with the currently active company
    @item.company = get_current_company

    # Handle any other associations or initial setup 
    # For example, if there's user information to be added
    @item.user = current_user if defined?(current_user)
    
    
    # ABSTRACTED/REUSABLE HANDLING (e.g. Concerns, etc.)
    ##################
    
    # CONCERNS
    # Maybe there's a concern for handling attachments or images?
    # @item = handle_attachments(@item)

    # OTHER (?)
    # ...    


    # EXECUTE & RESPOND
    ##################
    
    # Save the item and render response
    if @item.save
      render json: @item, status: :created
    else
      render json: @item.errors, status: :unprocessable_entity
    end
    
  end

  # ... Other actions ...

  private

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

```
