Triple Nested Forms in Rails

nested-forms $ rails g scaffold show name:string
nested-forms $ rails g model season number:integer show:references
# models/show.rb
class Show < ApplicationRecord
has_many :seasons
accepts_nested_attributes_for :seasons
end
# models/season.rb
class Season < ApplicationRecord
belongs_to :show, optional: true
end
# controllers/shows_controller.rb
def new
@show = Show.new
@show.seasons.build
end
...private
def show_params
params.require(:show).permit(:name,
:seasons_attributes => [:number]
)
end
<%= form_with(model: show, local: true) do |form| %>  # Show name and label  <%= form.fields_for :seasons do |s| %>
<%= s.label :number %>
<%= s.number_field :number %>
<% end %>
# Submit Button<% end %>
nested-forms $ rails g model episode title:string season:references
# models/season.rb
class Season < ApplicationRecord
belongs_to :show, optional: true
has_many :episodes
accepts_nested_attributes_for :episodes
end
# models/episode.rb
class Episode < ApplicationRecord
belongs_to :season, optional: true
end
# controllers/shows_controller.rb
def new
@show = Show.new
@show.seasons.build.episodes.build
end
private def show_params
params.require(:show).permit(:name,
:seasons_attributes => [:number,
:episodes_attributes => [:title]
]
)
end
<%= form_with(model: show, local: true) do |form| %># Show name and label  <%= form.fields_for :seasons do |s| %>
<%= s.label :number %>
<%= s.number_field :number %>
<%= s.fields_for :episodes do |e| %>
<%= e.label :title %>
<%= e.text_field :title %>
<% end %>
<% end %># Submit Button<% end %>

--

--

Web Developer, Marathon Runner, Coffee Drinker.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store