← Back to the explorable

A note feature, with the boundaries visible

This companion connects the fragments in Inside a Click. It targets Rails 8.1. It is an illustrative feature to add to an authenticated Rails application, not a complete login implementation or a claim that the explorable runs Ruby.

Assumptions: a users table already exists; ApplicationController provides current_user and require_login; require_login redirects an anonymous visitor and stops the action; normal Rails CSRF protection is enabled. If using the Rails authentication generator, adapt these names to its generated authentication concern and Current.user. Do not define a second incompatible login system.

1. Define the storage invariant

# db/migrate/TIMESTAMP_create_notes.rb
class CreateNotes < ActiveRecord::Migration[8.1]
  def change
    create_table :notes do |t|
      t.references :user, null: false, foreign_key: true
      t.string :title, null: false
      t.timestamps
    end
  end
end

The foreign key rejects references to a nonexistent user. The index generated for user_id helps scoped lookups. NOT NULL rejects missing SQL values, but does not reject an empty string or enforce a length of 100. The model below provides friendly validation. If every database writer must enforce nonblank and maximum-length rules, add database-appropriate CHECK constraints too.

Run bin/rails db:migrate in the intended environment. Inspect the resulting schema. Production migrations need a deployment plan appropriate to table size and locking behavior.

2. Describe the model relationship

# app/models/note.rb
class Note < ApplicationRecord
  belongs_to :user
  validates :title, presence: true, length: { maximum: 100 }
end

# Add inside the existing app/models/user.rb class:
has_many :notes, dependent: :destroy

No uniqueness rule is needed here: a user may intentionally create two notes with the same title. Do not add a uniqueness validation unless the domain requires it; if it does, add the matching database constraint too.

3. Give the resource addresses

# config/routes.rb — inside Rails.application.routes.draw
resources :notes
root "notes#index"

bin/rails routes -g notes shows the verb/path/action mapping. Route nesting alone never establishes authorization.

4. Coordinate requests and enforce ownership

# app/controllers/notes_controller.rb
class NotesController < ApplicationController
  before_action :require_login
  before_action :set_note, only: %i[show edit update destroy]

  def index
    @notes = current_user.notes.order(created_at: :desc, id: :desc)
  end

  def show
  end

  def new
    @note = current_user.notes.build
  end

  def edit
  end

  def create
    @note = current_user.notes.build(note_params)
    if @note.save
      redirect_to @note, status: :see_other
    else
      render :new, status: :unprocessable_entity
    end
  end

  def update
    if @note.update(note_params)
      redirect_to @note, status: :see_other
    else
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    @note.destroy!
    redirect_to notes_path, status: :see_other
  end

  private

  def set_note
    @note = current_user.notes.find(params[:id])
  end

  def note_params
    params.expect(note: [:title])
  end
end

The authenticated identity determines the owner. Input cannot set user_id. Each member lookup is scoped to that identity, so another user's note produces a not-found outcome. If the app later supports sharing, replace this simple ownership rule with its explicit sharing policy.

destroy! makes an unexpected failed destruction visible instead of silently redirecting as though it succeeded. A production application should handle expected domain failures deliberately. A real list should add pagination once it can grow large.

5. Render accessible HTML

<!-- app/views/notes/_form.html.erb -->
<%= form_with model: note do |form| %>
  <% if note.errors.any? %>
    <div role="alert">
      <h2>Please fix these problems</h2>
      <ul>
        <% note.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <%= form.label :title %>
  <%= form.text_field :title, maxlength: 100, required: true %>
  <%= form.submit "Save note" %>
<% end %>

The browser constraints improve feedback, but the server validates independently. The form helper generates the action and fields, including Rails' normal authenticity protection. ERB escapes the displayed error messages.

<!-- app/views/notes/new.html.erb -->
<h1>New note</h1>
<%= render "form", note: @note %>
<%= link_to "All notes", notes_path %>

<!-- app/views/notes/edit.html.erb -->
<h1>Edit note</h1>
<%= render "form", note: @note %>
<%= link_to "Cancel", note_path(@note) %>

<!-- app/views/notes/show.html.erb -->
<h1><%= @note.title %></h1>
<%= link_to "Edit", edit_note_path(@note) %>
<%= button_to "Delete", note_path(@note), method: :delete %>
<%= link_to "All notes", notes_path %>

<!-- app/views/notes/index.html.erb -->
<h1>My notes</h1>
<%= link_to "New note", new_note_path %>
<ul>
  <% @notes.each do |note| %>
    <li><%= link_to note.title, note_path(note) %></li>
  <% end %>
</ul>

Put each labeled section in its own file. Rails' application layout supplies the document structure and CSRF meta tags. button_to uses a form for a destructive operation. The browser receives HTML, not the Ruby template source.

6. Check the important boundaries

These request-test examples assume user fixtures reader and other, a note fixture other_note belonging to other, and an app-specific sign_in helper that establishes a real authenticated session for integration tests.

class NotesFlowTest < ActionDispatch::IntegrationTest
  test "the authenticated user owns a newly created note" do
    sign_in users(:reader)

    assert_difference("users(:reader).notes.count", 1) do
      post notes_path, params: {
        note: { title: "Read", user_id: users(:other).id }
      }
    end
    assert_response :see_other
  end

  test "invalid input does not create a row" do
    sign_in users(:reader)
    assert_no_difference("Note.count") do
      post notes_path, params: { note: { title: "" } }
    end
    assert_response :unprocessable_entity
    assert_select "form"
  end

  test "a user cannot change someone else's note" do
    sign_in users(:reader)
    note = notes(:other_note)
    original_title = note.title

    # Rails test exception rendering must be configured to render rescuable
    # exceptions for the HTTP assertion, as in a normal generated test setup.
    patch note_path(note), params: { note: { title: "Changed" } }

    assert_response :not_found
    assert_equal original_title, note.reload.title
  end
end

Also test anonymous requests using the app's login contract, reads and deletes of other users' notes, successful updates, and browser form behavior. Normal Rails test configuration may disable forgery protection; do not mistake a passing request test for an explicit CSRF test. These snippets have not been executed against a real Rails app here because the explorable has no Rails runtime or authentication implementation.

Follow the successful POST

  1. The browser constructs a form request with its session cookie and authenticity token.
  2. The network carries it through the chosen secure connection.
  3. The proxy and application server deliver it to Rails.
  4. The router selects NotesController#create.
  5. Authentication establishes current_user; parameters permit only title.
  6. The association assigns the owner. Validation checks the title.
  7. Active Record inserts the row; the database enforces its constraints.
  8. Rails returns a 303 with the new note's location.
  9. The browser makes a GET; the scoped lookup retrieves the note.
  10. The server renders escaped HTML; the browser parses and draws it.

A failure after step 7 but before the browser receives step 8 is an ambiguous result to the client. A retry-safe creation API needs an operation identity and a durable deduplication design if duplicate notes are unacceptable.

References: Rails controllers, routing, Active Record, migrations, forms, security, testing.