我目前正試圖在學習rails的任務中構建一個非常簡單的嵌套表單應用程序。在這個應用程序我有三個模型legal_form
answer
和question
。我有我的answers.html.erb,設置如下:「param is missing or the value is empty」嵌套形式
<%= 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缺失或爲空:legal_form」。
我認爲這很可能是由於我在法律_表格控制器中強烈的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
@[email protected]_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
任何幫助,終於征服嵌套形式將不勝感激。我一直在抨擊我的頭,現在一個星期左右。提前謝謝了。
請出示你的'routes.rb'和全'legal_forms'控制器。 – 2014-12-05 08:54:51
@Зелёный非常感謝您的回覆!我已經添加到上面的問題。 – neanderslob 2014-12-05 09:06:09
請修復縮進。這有助於我們閱讀這些代碼。 – 2014-12-05 09:09:23