# Model Patterns

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

## Core Principles

Models handle persistence and associations. Business logic goes in Commands.

## Required Patterns

### Associations
```ruby
class User < ApplicationRecord
  belongs_to :organization
  has_many :posts, dependent: :destroy

  # Use has_many :through for many-to-many
  has_many :memberships
  has_many :groups, through: :memberships
end
```

### Validations
```ruby
class Post < ApplicationRecord
  validates :title, presence: true, length: { maximum: 255 }
  validates :slug, uniqueness: { scope: :organization_id }

  # Custom validations are fine
  validate :published_date_not_in_future
end
```

### Scopes
```ruby
class Post < ApplicationRecord
  scope :published, -> { where(state: 'published') }
  scope :recent, -> { order(created_at: :desc) }
  scope :by_author, ->(user) { where(author: user) }
end
```

## Anti-Patterns (NEVER DO)

### Business Logic in Models
```ruby
# BAD - Complex logic doesn't belong here
class Order < ApplicationRecord
  def process_payment
    # 50 lines of payment logic
  end
end

# GOOD - Delegate to command
class Commands::ProcessPayment < BaseCommand
  # Business logic here
end
```

### God Models
Keep models focused on data, not everything else.

## Testing Models

```ruby
class UserTest < ActiveSupport::TestCase
  describe User do
    subject { users(:example) }  # Use fixtures

    describe 'validations' do
      it 'requires email' do
        subject.email = nil
        assert_not subject.valid?
      end
    end
  end
end
```