ruby
46 lines · 9 steps
Nested survey forms in Rails
Two models wire up nested attributes, cascading deletes, and custom validations so a survey and its questions save as one unit.
Explained by
highlit
1class Survey < ApplicationRecord
2 has_many :questions, dependent: :destroy
3 has_many :respondents, dependent: :nullify
4
5 accepts_nested_attributes_for :questions,
6 allow_destroy: true,
7 reject_if: ->(attrs) { attrs["prompt"].blank? && attrs["id"].blank? }
8
9 validates :title, presence: true, length: { maximum: 200 }
10 validate :must_have_at_least_one_question
11
12 private
13
14 def must_have_at_least_one_question
15 return if questions.reject(&:marked_for_destruction?).any?
16
17 errors.add(:base, "Add at least one question before publishing")
18 end
19end
20
21class Question < ApplicationRecord
22 belongs_to :survey
23 has_many :choices, dependent: :destroy
24
25 accepts_nested_attributes_for :choices,
26 allow_destroy: true,
27 reject_if: :blank_choice?
28
29 enum :kind, { single_choice: 0, multiple_choice: 1, free_text: 2 }
30
31 validates :prompt, presence: true
32 validate :choices_required_for_choice_kinds
33
34 private
35
36 def blank_choice?(attributes)
37 attributes["label"].blank?
38 end
39
40 def choices_required_for_choice_kinds
41 return if free_text?
42 return if choices.reject(&:marked_for_destruction?).size >= 2
43
44 errors.add(:choices, "must include at least two options")
45 end
46end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1accepts_nested_attributes_for with reject_if lets one form build parents and children together while silently dropping empty entries.
- 2Counting records after filtering marked_for_destruction? gives accurate validations even mid-form when rows are flagged for deletion.
- 3dependent: matters for intent — :destroy removes children while :nullify just unhooks them without deleting.
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
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
ruby
class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true, counter_cache: true belongs_to :author, class_name: "User"
How polymorphic comments work in Rails
polymorphic-association
concerns
counter-cache
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/nested-survey-forms-in-rails-explained-ruby-e103/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.