Rails 5.1中的form_with方法是用于生成表单的辅助方法。它可以用于创建包含多个嵌套子窗体的表单。在三重嵌套子窗体中,下级子窗体未继承属性且未保存的问题可能是由于表单的嵌套关系或数据模型的关联设置不正确导致的。
要解决这个问题,首先需要确保数据模型之间的关联设置正确。在Rails中,可以使用has_many、belongs_to等关联方法来定义模型之间的关系。确保父级模型正确地关联到子级模型,并且子级模型正确地关联到孙子级模型。
其次,需要在控制器中正确地构建表单对象。在三重嵌套子窗体中,需要在控制器中创建父级对象、子级对象和孙子级对象,并将它们正确地关联起来。可以使用build方法来构建关联对象。
最后,在视图中正确地渲染表单。在form_with方法中,需要使用fields_for方法来渲染子级和孙子级表单。确保正确地嵌套子级和孙子级表单,并正确地设置表单字段的名称。
以下是一个示例代码,演示了如何在Rails 5.1中创建三重嵌套子窗体:
# 数据模型
class Parent < ApplicationRecord
has_many :children
accepts_nested_attributes_for :children
end
class Child < ApplicationRecord
belongs_to :parent
has_many :grandchildren
accepts_nested_attributes_for :grandchildren
end
class Grandchild < ApplicationRecord
belongs_to :child
end
# 控制器
class ParentsController < ApplicationController
def new
@parent = Parent.new
@parent.children.build
@parent.children.each do |child|
child.grandchildren.build
end
end
def create
@parent = Parent.new(parent_params)
if @parent.save
# 保存成功的处理逻辑
else
# 保存失败的处理逻辑
end
end
private
def parent_params
params.require(:parent).permit(children_attributes: [:id, :name, grandchildren_attributes: [:id, :name]])
end
end
# 视图
<%= form_with(model: @parent, local: true) do |form| %>
<%= form.fields_for :children do |child_form| %>
<%= child_form.text_field :name %>
<%= child_form.fields_for :grandchildren do |grandchild_form| %>
<%= grandchild_form.text_field :name %>
<% end %>
<% end %>
<%= form.submit %>
<% end %>
在上述示例中,Parent模型与Child模型之间是一对多的关系,Child模型与Grandchild模型之间也是一对多的关系。在控制器的new方法中,通过build方法构建了父级对象、子级对象和孙子级对象。在视图中使用fields_for方法嵌套渲染了子级和孙子级表单。
对于腾讯云相关产品和产品介绍链接地址,由于要求不能提及具体的云计算品牌商,无法给出具体的推荐。但可以参考腾讯云的云计算产品,如云服务器、云数据库、云存储等,以满足不同场景下的需求。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云