gpt4 book ai didi

ruby-on-rails - Rails 4 嵌套形式。

转载 作者:行者123 更新时间:2023-12-02 20:55:53 26 4
gpt4 key购买 nike

我正在为客户构建动态表单。一个表格有许多表格问题,而表格问题又有许多表格答案。到目前为止,我可以在 Active Admin 中很好地创建所有内容,并通过应用程序界面上的显示操作将其显示出来。这是我遇到的问题。我想显示表单标题(正在运行)、表单问题(正在运行)以及用于动态提交新表单答案的输入字段(这是不起作用的部分)。我觉得在嵌套表单方面我已经用尽了一切。我将在下面发布我的代码。

表格

<%= form_for @form do |f| %>
<div class="field">
<h1><%= @form.name %></h1>
</div>
<%= f.fields_for :form_questions do |ff| %>
<div class="field">
<%= ff.label :title %>
<%= ff.text_field :form_answers %>
</div>
<% end %>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>

这是模型

class Form < ActiveRecord::Base
has_many :form_questions, dependent: :destroy
accepts_nested_attributes_for :form_questions, allow_destroy: true
end
<小时/>
class FormQuestion < ActiveRecord::Base
belongs_to :form
has_many :field_types
has_many :form_answers, dependent: :destroy
accepts_nested_attributes_for :field_types
accepts_nested_attributes_for :form_answers
end
<小时/>
class FormAnswer < ActiveRecord::Base
belongs_to :form_question
end
<小时/>

还有我的表单 Controller

class FormsController < ApplicationController

def new
@form = Form.new
# form_questions = @form.form_questions.build
# form_answers = form_questions.form_answers.build
end

def create
@form = Form.new(form_params)
end

def index
@forms = Form.includes(:form_questions).all
end

def show
@form = Form.find(params[:id])
end

def edit
@form = Form.find(params[:id])
end

def form_params
params.require(:form).permit(:id, :name, form_questions_attributes: [:title, form_answers_attributes: [:answer]])
end


end

最佳答案

首先,您应该在 new 方法中取消注释这两行。我猜它们是正确的。

def new
@form = Form.new
@form_questions = @form.form_questions.build
@form_answers = @form_questions.form_answers.build
end

并且在您的创建操作中,您没有保存数据

def create
@form = Form.new(form_params)
if @form.save
.....
else
.....
end
end

其次,您的表单代码应如下所示

<%= form_for @form do |f| %>
<div class="field">
<h1><%= @form.name %></h1>
</div>
<%= f.fields_for @form_questions do |ff| %>
<div class="field">
<%= ff.label :title %>
<%= ff.text_field :title %>
</div>
<%= ff.fields_for @form_answers do |fa| %> #Here comes the important step
<div class="field" %>
<%= fa.label :answer %>
<%= fa.text_field :answer %>
</div>
<% end %>
<% end %>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>

关于ruby-on-rails - Rails 4 嵌套形式。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25120956/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com