我将参加茧宝石中的教程。在尝试创建厕所时,除非首先创建厕所,否则我添加的设施将无法保存。我原以为它本应该一起创建。有没有办法在创建厕所时保存设施?
不要混淆
class Toilet < ApplicationRecord
has_many :facilities
accepts_nested_attributes_for :facilities, reject_if: :all_blank, allow_destroy: true
end
class Facility < ApplicationRecord
belongs_to :toilet
end
马桶控制器
def new
@toilet = Toilet.new
end
def create
@toilet = Toilet.new(toilet_params)
if @toilet.save
redirect_to @toilet
else
render :new
end
end
private
def toilet_params
params.require(:toilet).permit(:name, :location, facilities_attributes: [:id, :name, :_destroy])
end
_form.html.erb
<%= f.simple_fields_for :facilities do |facility| %>
<%= render 'facility_fields', :f => facility %>
<% end %>
<div class='links'>
<%= link_to_add_association 'add facility', f, :facilities %>
</div>
<%= f.submit 'Save' %>
<% end %>
_facility_fields.html.erb
<div class='nested-fields'>
<%= f.inputs do %>
<%= f.input :name %>
<%= link_to_remove_association "remove facility", f %>
<% end %>
</div>
答案 0 :(得分:0)
我相信您的问题可能在_facility_fields.html.erb
...您的<% f.inputs do %>
看起来不合适或者设置错误。由于您已经有一个包含render
命令的do循环,因此您不应该需要此另一个do
循环。这也意味着您要从end
上方的模板中移除/div
内容。
_facility_fields.html.erb
<div class='nested-fields'>
<%= f.inputs do %> // Issue is this line
<%= f.input :name %>
<%= link_to_remove_association "remove facility", f %>
<% end %> // Remove this too afterwards
</div>