我正在尝试构建一个非常简单的嵌套表单应用程序,以学习rails。在这个应用程序中,我有三个模型legal_form
answer
和question
。我有我的answers.html.erb,设置如下:
<%= form_for (@legal_form) do |f| %>
<h1>Title <%= @legal_form.title %></h1>
<p><%= @legal_form.description %></p>
<ul>
<% @legal_form.questions.each do |question| %>
<%= fields_for question.answers.build do |q| %>
<li>
<%= question.question_content %>
<%= q.text_field :answer_content %>
</li>
<% end =%>
<% end %>
</ul>
<p><%= f.submit "Submit" %></p>
<% end %>
目前正在抓取我存储的三个问题并在它们旁边呈现文本输入框;工作没有问题。但是,当我提交值时,我得到“param is missing or empty:legal_form”。
我认为这很可能是由于legal_forms控制器中我强大的params配置,见下文。
class LegalFormsController < ApplicationController
before_action :find_legal_form, only: [:show, :edit, :update, :destroy, :answers]
def index
@legal_form = LegalForm.all.order("created_at DESC")
end
def show
end
def new
@legal_form=LegalForm.new
end
def create
@legal_form = LegalForm.new(legal_form_params)
if @legal_form.save
redirect_to @legal_form, notice: "Successfully created new legal form."
else
render 'new'
end
end
def edit
end
def update
if @legal_form.update(legal_form_params)
redirect_to @legal_form
else
render 'edit'
end
end
def destroy
@legal_form.destroy
redirect_to root_path, notice: "Successfully deleted form"
end
def answers
@questions=@legal_form.questions
@legal_form=LegalForm.find(params[:id])
end
private
def legal_form_params
params.reqire(:legal_form).permit(:title, :description, :questions_attribute => [:id, :question_number, :question_content, :_destroy, :answer_attributes => [:id, :answer_content, :question_id, :user_id]])
end
def find_legal_form
@legal_form=LegalForm.find(params[:id])
end
end
并且,如果它有用,这里是每个模型。
class Answer < ActiveRecord::Base
belongs_to :question
end
class LegalForm < ActiveRecord::Base
has_many :questions, :dependent => :destroy
has_many :answers, through: :entity_roles
accepts_nested_attributes_for :questions,
reject_if: proc { |attributes| attributes['question_content'].blank? },
allow_destroy: true
end
class Question < ActiveRecord::Base
belongs_to :legal_form
has_many :answers
accepts_nested_attributes_for :answers,
reject_if: proc { |attributes| attributes['question_content'].blank? },
allow_destroy: true
end
此外,根据要求,我的路线文件:
Rails.application.routes.draw do
resources :legal_forms do
member do
get 'answers'
end
end
resources :answers
root "legal_forms#index"
end
任何有助于最终征服嵌套表格的帮助将不胜感激。我一直在敲打我的脑袋,持续一周左右。非常感谢提前。
答案 0 :(得分:1)
尝试使用控制器
def legal_form_params
params.require(:legal_form).permit(...)
end
另外,question.answers.build将它添加到控制器的方法中并调用返回对fields_for的响应的对象
<强>更新强>
要通过此表单发送您的结果,应该是这样的
形式
<%= f.fields_for :answers do |q| %>
...
<% end =%>
在新方法中
def new
@legal_form=LegalForm.new
@answers = @legal_form.question.answers.build
end
def legal_form_params
params.require(:legal_form).permit! #temporarily
end
没试过,但想象一下它是如何工作的