Multiple Nested RESTful Resources


#1

I have a domain model with 3 resources: Surveys, Questions, Choices.
(Surveys have_many Questions; Questions have_many Choices. Questions
belong_to Survey; Choices belong_to Question)

Here is how I’ve set up the routes:


ActionController::Routing::Routes.draw do |map|

map.resources :surveys do |survey|
survey.resources :questions do |question|
question.resources :choices
end
end

I am getting an error when trying to display the relationship in the
surveys/show.rhtml view:


Title: <%=h @survey.title %>

Description: <%=h @survey.description %>

Created at: <%=h @survey.created_at %>

loop for displaying all questions for a survey

<% unless @survey.questions.empty? %>
<%= render :partial => “/questions/question/”, :collection =>
@survey.questions %>

# loop for displaying question choices
<% unless @question.choices.empty? %>
  <%= render :partial => "/choices/choice/", :collection =>

@question.choices %>
<% end %>

<%= link_to "Add choice", new_choice_url(@question.choices) %>

<% end %>

(The partials are both just displaying a single column “title” from the
questions and surveys table.)

This is the error:
“You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.choices”

Any thoughts on what I’m doing wrong?

I am very much a newbie, so if I’m missing any pertinent or supporting
info, please let me know. Thanks in advance.


#2

If Survey has_many Questions, then you probably don’t have a @question
variable in the Survey#show action, unless there is a default Question
or
I’m just misunderstanding something. Have you set @question? If not,
then
that’s your error.
It seems like the following bit should go in your _question.rhtml
partial,
not the show.rhtml:

<% unless @question.choices(params[@survey]).empty? %>
<%= render :partial => “/choices/choice/”, :collection => @
question.choices %>
<% end %>

and I believe you’ll need to use question instead of @question if inside
a
collection partial.

ed