导轨嵌套属性3级深度
我有模型series
seasons
和episodes
。从series/new
的形式我想创建一个系列,季节和情节一起。我正在阅读Rails Routing和Nested Forms指南,但我不知道我在做什么错,因为指南并未涵盖3级的深度。当使用嵌套表单时,Rails仅插入Series
和Season
值而不是Episode
值。导轨嵌套属性3级深度
我的方法更正确吗?我会很感激任何输入〜
# 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 %>
您需要从该系列机型移动accepts_nested_attributes_for :episodes
以来季节形式季节模型,<%= seasons_form.fields_for :episodes ... %>
是接受属性为episodes
这会在我的构建语句中抛出一个未定义的方法'episodes'。 – Dotol
更换
# 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
这很有道理实际上不能相信我想到的是,一旦我有权访问计算机,检查一下。 – Dotol
这[代码](https://github.com/rails/rails/blob/d0d7ce001bdbb0e5551da881caf8156c06238b84/activerecord/lib/active_record/nested_attributes.rb)显示了rails如何定义'accep_nested_attributes_for'。 如果'如果反射= _reflect_on_association(association_name)'是零, '提高引发ArgumentError, “没有协会发现名称\'#{association_name}”。它是否尚未定义的?”' 发生。 – kansiho
谢谢@Aoi_777我更新了原始帖子,以进一步详细说明剧集未如何保存 – Dotol
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
正如你已经使用has_many :episodes, :through => :seasons
,情节参数将里面hash
的seasons
。所以,你需要做一个细微的变化在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
注:这是静态的。对于动态对象构建,这里是一个很好的screencast
你是否在params散列中接收了episod的属性?如果是的话,那么你是否列入了插曲的属性? –
感谢您的回复,这是我的series_params:'def series_params params.require(:person).permit(:title,seasons_attributes:[:id,:title],episodes_attributes:[:id,:title]) end ' – Dotol