ruby 46 lines · 7 steps

Scoping a Rails API controller to Current.account

A JSON controller that keeps every project tenant-scoped and validates rich nested params.

Explained by highlit
1class ProjectsController < ApplicationController
2 before_action :set_project, only: %i[show update destroy]
3 
4 def create
5 @project = Current.account.projects.new(project_params)
6 
7 if @project.save
8 render :show, status: :created
9 else
10 render json: { errors: @project.errors }, status: :unprocessable_entity
11 end
12 end
13 
14 def update
15 if @project.update(project_params)
16 render :show
17 else
18 render json: { errors: @project.errors }, status: :unprocessable_entity
19 end
20 end
21 
22 private
23 
24 def set_project
25 @project = Current.account.projects.find(params[:id])
26 end
27 
28 def project_params
29 params.require(:project).permit(
30 :name,
31 :description,
32 :due_on,
33 tag_ids: [],
34 collaborator_emails: [],
35 tasks_attributes: [
36 :id,
37 :title,
38 :position,
39 :_destroy,
40 assignee_ids: [],
41 checklist: [:label, :done]
42 ],
43 metadata: {}
44 )
45 end
46end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Scoping queries through Current.account makes tenant isolation automatic instead of a per-action afterthought.
  2. 2Strong parameters can whitelist deeply nested and dynamic structures with arrays, hashes, and *_attributes.
  3. 3Returning validation errors with unprocessable_entity gives API clients a consistent contract for both create and update.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Scoping a Rails API controller to Current.account — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code