Forum: Ruby on Rails Multiple Nested RESTful Resources

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
(Guest)
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
    end
  end

...
------------------------------------------------------------

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

------------------------------------------------------------
<p>
  <b>Title:</b>
  <%=h @survey.title %>
</p>

<p>
  <b>Description:</b>
  <%=h @survey.description %>
</p>

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

# 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
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
This topic is locked and can not be replied to.