# Displaying Nested Objects

**URL:** <https://www.ruby-forum.com/t/displaying-nested-objects/184717>\
**Category:** Rails\
**Created:** [March 7, 2010, 10:14am UTC](https://www.ruby-forum.com/t/displaying-nested-objects/184717 "2010-03-07T10:14:48Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ObjectEvolution](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/b3f665/32.png) [@ObjectEvolution](https://www.ruby-forum.com/u/ObjectEvolution)\
**Post date:** [March 7, 2010, 10:14am UTC](https://www.ruby-forum.com/t/displaying-nested-objects/184717/1 "2010-03-07T10:14:48Z")

</div>

Hi,

I’ve got a question regarding my models in my Rails app. Let’s say I  
have an object:

User

which has\_many:

Thing1

and Thing1 has\_many:

Thing2

and Thing2 has\_one:

Thing3

When I go to display this in my template, like this:

\<% @user.thing1.each do |c| %\>

\<% end %\>

I get:

undefined method `name’ for nil:NilClass

I’m assuming this means there is no Thing3 object for this particular  
Thing2 object.

I just bought Agile Development with Rails and am starting to go  
through that…it’s surely noob question but can someone set me  
straight?

Thanks!

Jon

| Title | Date | Event |
| --- | --- | --- |
| \<%=h c.title %\> | \<%=h c.date %\> | \<% c.thing2.each do |be| %\> \<%=h be.thing3.name %\> \<% end %\> 

| Thing2 |
| --- |
| \<%=h be.workout\_type %\> |

 |

---

<div class="post-metadata">

**Author:** ![ObjectEvolution](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/b3f665/32.png) [@ObjectEvolution](https://www.ruby-forum.com/u/ObjectEvolution)\
**Post date:** [March 7, 2010, 1:03pm UTC](https://www.ruby-forum.com/t/displaying-nested-objects/184717/2 "2010-03-07T13:03:57Z")

</div>

On 7 March 2010 00:26, ObjectEvolution [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> undefined method `name’ for nil:NilClass
> 
> I’m assuming this means there is no Thing3 object for this particular  
> Thing2 object.

you’re quite correct - there’s no “thing3” linked to a given “thing 2”.  
If there _supposed_ to be an associated object there, then something’s  
gone wrong when you’ve created your objects, but if it’s a case that  
there may or may not be a Thing3, then a simple “guard” would suffice.

\<%=h be.thing3.name if be.thing3 %\>

---

<div class="post-metadata">

**Author:** ![ObjectEvolution](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/b3f665/32.png) [@ObjectEvolution](https://www.ruby-forum.com/u/ObjectEvolution)\
**Post date:** [March 7, 2010, 7:13pm UTC](https://www.ruby-forum.com/t/displaying-nested-objects/184717/3 "2010-03-07T19:13:17Z")

</div>

Perfect…thanks!
