accepts_nested_attributes_for 与 has_many 一起使用时只显示一条记录
accepts_nested_attributes_for only display one record when used with has_many
我的模特
class Game < ApplicationRecord
has_many :rounds
accepts_nested_attributes_for :rounds
end
class Round < ApplicationRecord
belongs_to :game
end
控制器
def new
@game = Game.new
3.times { @game.rounds.build }
end
查看
<%= form_with scope: :game, url: games_path, local: true do |form| %>
<p>
<%= form.label :title %><br>
<%= form.text_field :title %>
</p>
<p>
<%= form.label :game_date %><br>
<%= form.date_field :game_date %>
</p>
<ul>
<%= form.fields_for :rounds do |builder| %>
<li>
<%= builder.label :title %>
<%= builder.text_field :title %>
<%= builder.label :order %>
<%= builder.text_field :order %>
</li>
<% end %>
</ul>
<p>
<%= form.submit %>
</p>
<% end %>
以上代码在新建3条记录时只生成一条"round"条记录。
我在 rails 5.2.1
原来你必须使用 form_for 而不是新的 form_with。
这是因为你在使用表单时有不同的对象(formbuilder)。
<%= form_with model: @game, local: true do |form| %>
或者
<%= form_with scope: @game, url: games_path, local: true do |form| %>
而不是
<%= form_with scope: :game, url: games_path, local: true do |form| %>
产生了想要的结果。查看 this blog 以更好地理解。
我的模特
class Game < ApplicationRecord
has_many :rounds
accepts_nested_attributes_for :rounds
end
class Round < ApplicationRecord
belongs_to :game
end
控制器
def new
@game = Game.new
3.times { @game.rounds.build }
end
查看
<%= form_with scope: :game, url: games_path, local: true do |form| %>
<p>
<%= form.label :title %><br>
<%= form.text_field :title %>
</p>
<p>
<%= form.label :game_date %><br>
<%= form.date_field :game_date %>
</p>
<ul>
<%= form.fields_for :rounds do |builder| %>
<li>
<%= builder.label :title %>
<%= builder.text_field :title %>
<%= builder.label :order %>
<%= builder.text_field :order %>
</li>
<% end %>
</ul>
<p>
<%= form.submit %>
</p>
<% end %>
以上代码在新建3条记录时只生成一条"round"条记录。
我在 rails 5.2.1
原来你必须使用 form_for 而不是新的 form_with。
这是因为你在使用表单时有不同的对象(formbuilder)。
<%= form_with model: @game, local: true do |form| %>
或者
<%= form_with scope: @game, url: games_path, local: true do |form| %>
而不是
<%= form_with scope: :game, url: games_path, local: true do |form| %>
产生了想要的结果。查看 this blog 以更好地理解。