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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Form objects let one validatable class coordinate a workflow that touches several database tables.
  2. 2Wrapping multiple create! calls in a transaction makes the whole signup atomic — all rows commit or none do.
  3. 3Catching RecordInvalid and copying its errors back onto the form gives the view a single, unified place to read failures.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a Rails form object spans two models — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code