我很感兴趣为什么我在RoR中的嵌套表单不会保存子对象:(
现在,它只保存父(打印机)值并使子(Color)在第二次渲染时消失(错误)!我究竟做错了什么?
父模型
class Printer < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
validates :model, presence: true
has_many :colors, dependent: :destroy
accepts_nested_attributes_for :colors
end
儿童模特
class Color < ActiveRecord::Base
belongs_to :printer
validates :color, presence: true
end
查看(new.html.erb)
<%= form_for @printer do |p|%>
<%= p.text_field :model %>
<%= p.fields_for :colors do |color|%>
<%= color.text_field :color%>
<% end %>
<%= p.submit "Add"%>
<% end %>
和控制器
def create
@printer = current_user.printers.build(printer_params)
if @printer.save
redirect_to @current_user
else
render 'new'
end
end
def new
@printer = Printer.new
@printer.colors.build
end
private
def printer_params
params.require(:printer).permit(:model)
end
修改 这个帮助
private
def printer_params
params.require(:printer).permit(:model, colors_attributes: [:color])
end
答案 0 :(得分:1)
使用嵌套表单时,您需要指定哪些嵌套属性应列入白名单:
def printer_params
params.require(:printer).permit(:model, colors_attributes: [:color])
end
您可以在Rails Guides - Form Helpers - the controller section和RoR API documentation - Strong Parameters
了解更多相关信息