I'm currently trying to build a really simple nested form app in my quest to learn rails. In this app I have three models legal_form
answer
and question
. I have my my answers.html.erb, set up as follows:
<%= 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 %>
Which currently grabs the three questions I have stored and renders text input boxes next to them; works without a problem. However, when I submit the values, I get the "param is missing or empty: legal_form".
I figure that this is most likely due to my strong params configuration in the legal_forms controller, see below.
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
And, in case it's helpful, here are the models for each.
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
Also, as requested here's my routes file:
Rails.application.routes.draw do
resources :legal_forms do
member do
get 'answers'
end
end
resources :answers
root "legal_forms#index"
end
Any help to finally conquer nested forms would be greatly appreciated. I've been banging my head against it off and on for about a week now. Many thanks in advance.
Title <%= f.title %>
<%= f.description %>
` – theLibertine Dec 05 '14 at 09:11