Forum: Ruby on Rails Multiple Nested RESTful Resources

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
on 2007-01-27 03:35
(Received via mailing list)
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


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

  <%=h @survey.title %>

  <%=h @survey.description %>

  <b>Created at:</b>
  <%=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.
Ed Hickey (Guest)
on 2007-01-27 19:57
(Received via mailing list)
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
I'm just misunderstanding something.  Have you set @question?  If not,
that's your error.
It seems like the following bit should go in your _question.rhtml
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
collection partial.

This topic is locked and can not be replied to.