Reputation: 55
This my first time asking a question so please go easy one me :-p
I am following the examples on http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials (Section 3.4.5 Rendering Collections) for rendering collections using partials. The code looks simple, but clearly I am missing something.
models/expert.rb contains the line:
attr_accessible :name
experts_controller.rb contains the following line in the index method:
@experts = Expert.all
views/experts/index.html.erb contains the following line:
<%= render :partial => "expert", :collection => @experts %>
views/experts/_expert.html.erb contains:
<%= expert.name %>
Upon viewing the index page in my browser I get the following error:
NoMethodError in Experts#index
undefined method `name' for nil:NilClass
I have been working on this for an hour and am completely stumped :-/ What little thing am I missing?
---Clarification---
Running '<%= debug @experts %>' within index.html.erb produces the following output:
- !ruby/object:Expert
attributes:
id: 1
name: Bob Smith
slug: bob-smith
created_at: '2012-03-11 18:37:11.791118'
updated_at: '2012-03-11 18:55:58.179629'
changed_attributes: {}
previously_changed: {}
attributes_cache: {}
marked_for_destruction: false
destroyed: false
readonly: false
new_record: false
- !ruby/object:Expert
attributes:
id: 2
name: Steve Kamp
slug: steve-kamp
created_at: !!null
updated_at: !!null
changed_attributes: {}
previously_changed: {}
attributes_cache: {}
marked_for_destruction: false
destroyed: false
readonly: false
new_record: false
Upvotes: 1
Views: 1995
Reputation: 43103
The exception almost certainly means that there are no experts, so @experts
is an empty array. Have you created any expert records yet?
Also, just so you'll know, to render a collection of objects the way you're doing there's a nice shortcut:
render @experts
Upvotes: 1