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 "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
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.