Search code examples
ruby-on-railsnested-formsform-fornested-form-for

Rails 3 form_for Nested Routes


I`m trying to do a form_for with nested routes following the example of Blog and Comments from Ruby Guide(http://guides.rubyonrails.org/getting_started.html#adding-a-route-for-comments).

I`m doing an application to create surveys with a lot of kind of questions, the questions are in a group and each question has one o more options of answers.

This is the reoutes.rb

  resources :groups do
    resources :questions do
      resource :answers
    end
  end

The controllers are working well, and when I show a group created there is possible to see thes questions and create questions with the nested form_for bellow:

groups/show.html.erb

<h2>Group: <%= @group.desc %> </h2>
<h3>Questions</h3>
<% @group.questions.each do |q| %>
   <%= q.desc%> <%= link_to 'Destroy question', [@group, q], :confirm => 'Are you sure?', :method => :delete %> <br/>
<%end%>

<h4>New question</h4>
<%= form_for([@group, @group.questions.build]) do |f| %>
  <div class="field">
    <%= f.label 'Label: '%>
    <%= f.text_field :desc, :size => 100%>
    <%= f.submit 'Create question'  %>
  </div>
<% end %>
<br />

Now I need to show the answers and some way to insert the anwsers to that question. To show the answers works good with q.answers.each inside @group.questions.each block. But what I have to do is to make a form_for for answer, I tried the code bellow but does`nt works:

groups/show.html.erb

...
<% @group.questions.each do |q| %>
   <%= q.desc%> <%= link_to 'Destroy question', [@group, q], :confirm => 'Are you sure?', :method => :delete %> <br/>
  <!-- New answer -->
  <%= form_for([q, q.answers.build]) do |f| %>
  <div class="field">
    <%= f.label 'Label: '%>
    <%= f.text_field :desc, :size => 100%>
    <%= f.submit 'Create answer'  %>
  </div>
<% end %> 

<%end%>
<h4> New question<h4>
...

The Rails gives a error:

undefined method `question_answers_path'

when I try to use form_for([q, q.answers.build]) .

Any help?


Solution

  • The order you specify the objects in the form for matters, you have the resources nested under groups then questions then finally answers. You need to use something like form_for [g,q,q.answers.build]. If that dosnt work edit your post to include the contents of rake routes and we can go from there.