ruby
41 lines · 7 steps
How a Rails form object spans two models
A plain Ruby class uses ActiveModel to validate one form that creates a Company and its User in a single transaction.
Explained by
highlit
1class RegistrationForm
2 include ActiveModel::Model
3 include ActiveModel::Attributes
4
5 attribute :company_name, :string
6 attribute :user_name, :string
7 attribute :email, :string
8 attribute :password, :string
9
10 validates :company_name, presence: true
11 validates :user_name, presence: true
12 validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
13 validates :password, length: { minimum: 8 }
14
15 def save
16 return false unless valid?
17
18 ActiveRecord::Base.transaction do
19 @company = Company.create!(name: company_name)
20 @user = @company.users.create!(
21 name: user_name,
22 email: email,
23 password: password
24 )
25 end
26 true
27 rescue ActiveRecord::RecordInvalid => e
28 e.record.errors.each do |error|
29 errors.add(error.attribute, error.message)
30 end
31 false
32 end
33
34 def company
35 @company
36 end
37
38 def user
39 @user
40 end
41end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Form objects let one validatable class coordinate a workflow that touches several database tables.
- 2Wrapping multiple create! calls in a transaction makes the whole signup atomic — all rows commit or none do.
- 3Catching RecordInvalid and copying its errors back onto the form gives the view a single, unified place to read failures.
Related explainers
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
php
<?php namespace App\Console\Commands;
Releasing stale document locks in Laravel
artisan-command
transactions
row-locking
Intermediate
6 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-rails-form-object-spans-two-models-explained-ruby-9dc7/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.