LearningRoR
LearningRoR

Reputation: 27232

Can't find name of parent model even when inside of nested route?

I'm creating a child by my nested form and I know the routes work because I'm on it.

resources :surveys do
  resources :questions
end

I selected the first survey to add questions too and than I want to display the name of the survey on the page:

class QuestionsController < ApplicationController

  def new
    @Survey = Survey.find(params[:id])
    @question = Question.new
  end
end

http://localhost:3000/surveys/1/questions/new

<div><%= @survey.name %></div> # show this

<div>
 <%= simple_form_for(@question do |f| %>
  <%= f.button :submit, "Done" %>
 <% end %>
</div>

This gives me the error:

ActiveRecord::RecordNotFound in SurveysController#new

Couldn't find Survey without an ID

app/controllers/questions_controller.rb:7:in `new'

{"survey_id"=>"1"}

Why? What is going on here?

Upvotes: 1

Views: 109

Answers (1)

JeanMertz
JeanMertz

Reputation: 2270

Exactly what the error is telling you. If you want to find the "parent" model by id, you need to use *parent*_id, so in this case that would be:

@Survey = Survey.find(params[:survey_id])

The id param is reserved for the current controller, which in this case refers to the id of a question, not a survey.

Upvotes: 1

Related Questions