Petros Kyriakou
Petros Kyriakou

Reputation: 5343

Nested routes form_for partial not working for new and edit actions - Rails 4

I used the generator to scaffold categories and questions.

my routes.rb

  resources :categories do
    resources :questions do
      resources :choices, only: [:index]
    end
  end

my problem occurs when i try to add or edit a question.

here is my partial form, before you ask the relationship works ok.

<%= form_for [@question.category, @question] do |f| %>
  <% if @question.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@question.errors.count, "error") %> prohibited this question from being saved:</h2>

      <ul>
      <% @question.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :question_type %><br>
    <%= f.text_field :question_type %>
  </div>
  <div class="field">
    <%= f.label :explanation %><br>
    <%= f.text_field :explanation %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_field :description %>
  </div>
  <div class="field">
    <%= f.label :category_id %><br>
    <%= f.text_field :category_id %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

what must i change for it to work? for now i get,

undefined method `questions_path'

Upvotes: 0

Views: 656

Answers (3)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

Add this line to your category.rb model file:

accepts_nested_attributes_for :questions

Also, in your controller:

@category = Category.find(params[:category_id])
@question = Question.new(category: @category)

and form:

<%= form_for([@category, @question]) do |f| %>

Upvotes: 1

Prashant4224
Prashant4224

Reputation: 1601

Try this

UPDATE

Controller

@category = Category.find(params[:category_id])
@question = @category.questions.new

_form

<%= form_for([@category, @question]) do |f| %>

Reference

Upvotes: 2

Nitin
Nitin

Reputation: 7366

You should pass parent and then build child for same for new object.

<%= form_for [@category, @category.questions.build] do |f| %>

To edit:

<%= form_for [@category, @category.questions.first_or_your_object] do |f| %>

Like this :

<% if @category.new_record? %>
  <%= form_for [@category, @category.questions.build] do |f| %>
<% else %>
  <%= form_for [@category, @category.questions.first_or_your_object] do |f|
<% else %>

Also add in your category model:

accepts_nested_attributes_for :questions

Upvotes: 1

Related Questions