Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Active Record Associations in Rails Using Associations in Your App Rendering Collections

Brad Givens
Brad Givens
6,621 Points

Rendering Partial -

I'm not sure where I'm going wrong here, I've successfully rendered partials in other examples before outside of Treehouse. I think I'm getting confused with the pet/name variables but I've tried to alternate which ones go where.

Any ideas?

Thanks,

app/views/owners/show.html.erb
<h1>Owner: <%= @owner.name %></h1>

<div id="pets">
  <h2>Pets</h2>
  <% @owner.pets.each do |name| %>
    <%= render partial: "pets/pet" %>
  <% end %>

</div>
app/views/pets/_pet.html.erb
<div>
  <strong>Name:</strong>
  <%= Pet.name %>
</div>

1 Answer

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

You've got a couple issues here.

  • You need to set the local pet variable that will be used within the partial from your main template. There are several ways to do this, but here's one that's compatible with the code you already have:
  <% @owner.pets.each do |pet| %>
    <%= render partial: "pets/pet", locals: {pet: pet} %>
  <% end %>
  • Your _pet partial is actually trying to call a class method on the Pet class, not an instance of the Pet class. Local variables are always named in lower-case. Starting with upper-case indicates a constant, like a class name.

You should review the preceding video for details on getting local variables into the partial view.