Rails嵌套属性3级深度

时间:2017-09-05 02:30:09

标签: ruby-on-rails nested-forms nested-attributes

我有模型series seasonsepisodes。从series/new格式开始,我想一起创作一个系列,季节和剧集。我正在阅读Rails RoutingNested Forms指南,但我不知道我做错了什么,因为指南没有涵盖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 %>

3 个答案:

答案 0 :(得分:1)

替换

# 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

答案 1 :(得分:1)

series.rb

ChildA

season.rb

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

accepts_nested_attributes_for :seasons
accepts_nested_attributes_for :episodes

episode.rb

belongs_to :series
has_many :episodes, dependent: :destroy

accepts_nested_attributes_for :episodes

正如您使用belongs_to :season 一样,剧集参数将位于has_many :episodes, :through => :seasons的{​​{1}}内。所以你需要在hash方法中稍作改动:

系列控制器

seasons

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

答案 2 :(得分:0)

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

的属性