铁轨嵌套属性3级深度



i具有型号series seasonsepisodes。从series/new表格中,我想一起创建一个系列,季节和情节。我正在阅读Rails路由和嵌套表格指南,但我不知道我在做什么错,因为该指南不涵盖3级深度。当使用嵌套表单时,Rails仅插入SeriesSeason,而不是Episode

我的方法甚至正确吗?我感谢任何输入〜

# 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

系列/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 %>

替换

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

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

series.rb

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

季节.rb

belongs_to :series
has_many :episodes, dependent: :destroy
accepts_nested_attributes_for :episodes

episode.rb

belongs_to :season

当您使用has_many :episodes, :through => :seasons时,情节参数将在seasonshash内部。因此,您需要对series_params方法进行略微更改:

系列控制器

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

注意:它是静态的。对于动态对象构建,这是一个很好的屏幕截图

您需要将accepts_nested_attributes_for :episodes从系列模型移动到季节模型,因为季节形式,<%= seasons_form.fields_for :episodes ... %>正在接受episodes

的属性

最新更新