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
require "csv" class SalesReport def initialize(path)
Aggregating CSV sales data in Ruby
data-aggregation
memoization
group_by
Intermediate
6 steps
ruby
module DurationFormatter UNITS = [ ['week', 604_800], ['day', 86_400],
Turning seconds into human-readable durations in Ruby
greedy-decomposition
modular-arithmetic
formatting
Intermediate
7 steps
javascript
const express = require('express'); const v1 = express.Router();
Versioning an API with Express Routers
api versioning
routing
modularity
Intermediate
10 steps
ruby
class Comment < ApplicationRecord belongs_to :post belongs_to :author, class_name: "User"
Live-updating comments with Turbo in Rails
turbo-streams
callbacks
associations
Intermediate
8 steps
ruby
require 'json' require 'set' class SensitiveScrubber
Recursively scrubbing secrets from JSON
recursion
data-masking
pattern-matching
Intermediate
7 steps
ruby
class ReportBatcher BATCH_SIZE = 500 def initialize(account)
Batching monthly email summaries in Rails
batching
service-object
background-jobs
Intermediate
7 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.