ruby 34 lines · 7 steps

The new/create pattern in a Rails controller

How a Rails controller scopes records to the current account and handles the save-or-re-render flow.

Explained by highlit
1class ProjectsController < ApplicationController
2 def new
3 @project = current_account.projects.build
4 load_form_collections
5 end
6 
7 def create
8 @project = current_account.projects.build(project_params)
9 
10 if @project.save
11 redirect_to @project, notice: "Project created."
12 else
13 load_form_collections
14 render :new, status: :unprocessable_entity
15 end
16 end
17 
18 private
19 
20 def load_form_collections
21 @clients = current_account.clients
22 .includes(:contacts)
23 .active
24 .order(:name)
25 
26 @team_members = current_account.memberships
27 .includes(:user)
28 .order("users.last_name")
29 end
30 
31 def project_params
32 params.require(:project).permit(:name, :client_id, :lead_id, :due_on)
33 end
34end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Building records through an association like current_account.projects keeps every query and creation scoped to the right tenant automatically.
  2. 2Re-rendering :new with an unprocessable_entity status on failure preserves user input and validation errors while signaling the error correctly.
  3. 3Extracting shared setup like form collections into a private method keeps new and create in sync without duplication.

Related explainers

Share this explainer

Here's the card — post it anywhere.

The new/create pattern in a Rails controller — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code