Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Nested Attributes 3 level depth

I have the models series seasons and episodes. From within series/new form I want to create a series, season and episode all together. I'm reading Rails Routing and Nested Forms guides but I don't know what I'm doing wrong as the guide doesn't cover a 3 level depth. When using the nested form, Rails is only inserting the Series and Season values but not the Episode values.

Is my approach even correct? I'd appreciate any input~

# series.rb
has_many :seasons, dependent: :destroy
has_many :episodes, :through => :seasons
accepts_nested_attributes_for :seasons
accepts_nested_attributes_for :episodes

# season.rb
belongs_to :series
has_many :episodes, dependent: :destroy

# episode.rb
belongs_to :season

# routes.rb
resources :series, except: [:show, :new] do
  resources:seasons, except: [:show], path: '' do
    resources :episodes, path: ''
  end
end

series/new.html.erb

<%= form_for @series do |f| %>
    <%= f.text_field :title %>
    <%= f.fields_for :seasons do |seasons_form| %>
      <%= seasons_form.text_field :title %>
      <%= seasons_form.fields_for :episodes do |episodes_form| %>
        <%= episodes_form.text_field :title %>
      <% end %>
    <% end %>
  <% end %>
like image 642
Dotol Avatar asked Dec 03 '25 07:12

Dotol


1 Answers

series.rb

has_many :seasons, dependent: :destroy
has_many :episodes, :through => :seasons

accepts_nested_attributes_for :seasons
accepts_nested_attributes_for :episodes

season.rb

belongs_to :series
has_many :episodes, dependent: :destroy

accepts_nested_attributes_for :episodes

episode.rb

belongs_to :season

As you have used has_many :episodes, :through => :seasons , episodes parameters will be inside the hash of seasons. So you need to make a slight change in series_params method:

series controller

def new
  @series = Series.new
  #build objects of nested
  @season = @series.seasons.build  
  @episod = @season.episods.build
end

def series_params 
  params.require(:series).permit(:title, 
   seasons_attributes: [:id, :title, episodes_attributes: [:id, :title]]) 
end

Note: It is static. For dynamic object building, here is a good screencast

like image 149
Hasmukh Rathod Avatar answered Dec 05 '25 23:12

Hasmukh Rathod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!