# Controller Patterns

*Note: This is a simplified example from a working project, adapted for demonstration purposes.*

## Core Principles

Controllers coordinate. They don't contain business logic.

## Required Patterns

### Basic Structure
```ruby
class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  def index
    @posts = policy_scope(Post).page(params[:page])
    authorize Post  # ALWAYS authorize
  end

  def create
    @post = current_organization.posts.build(post_params)
    authorize @post

    if @post.save
      redirect_to @post
    else
      render :new, status: :unprocessable_entity
    end
  end

  private

  def set_post
    @post = policy_scope(Post).find(params[:id])
  end

  def post_params
    # Rails 8 pattern
    params.expect(post: [:title, :content, :published])
  end
end
```

### Using Commands for Complex Logic
```ruby
def publish
  @post = policy_scope(Post).find(params[:id])
  authorize @post

  command = Commands::PublishPost.new(post: @post, user: current_user)

  if command.run
    redirect_to @post, notice: "Published successfully"
  else
    redirect_to @post, alert: command.errors.full_messages.join(", ")
  end
end
```

## Anti-Patterns (NEVER DO)

### Missing Authorization
```ruby
# BAD - No authorization
def show
  @post = Post.find(params[:id])
end

# GOOD - Always authorize
def show
  @post = policy_scope(Post).find(params[:id])
  authorize @post
end
```

### Business Logic in Controllers
Complex logic belongs in Commands, not controllers.

## Remember

- ALWAYS use Pundit authorization
- Delegate complex logic to Commands
- Let Rails handle format selection automatically
- Keep controllers thin