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

Figmints Delicious Design
Figmints Delicious Design
13,972 Points

Render error

I thought that I was following the directions, however this throws an error message with a huge stack saying the the render is wrong, What am I missing here?

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

<div id="pets">
  <h2>Pets</h2>
  <!-- YOUR CODE HERE -->
  <%= @owner.pets.each do |name| %>
    <%= render partial: "pets/pet", locals: {name: name} %>
  <%= end %>

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

1 Answer

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

There are a couple issues here. Here's the first:

<%= end %>

You should only use <%= %> if you want to insert the result of an expression into the template output. Which you never want to do with an end keyword. Use <% %> here instead.

Once you solve that, this code will cause a different error:

  <%= @owner.pets.each do |name| %>
    <%= render partial: "pets/pet", locals: {name: name} %>
  <% end %>

The code @owner.pets.each do |name| causes each Pet to be stored, one at a time, in a variable called name. name doesn't contain a name, it contains a Pet. So you should probably change the name of your name variable to pet:

  <%= @owner.pets.each do |pet| %>
    <%= render partial: "pets/pet", locals: {pet: pet} %>
  <% end %>

Once you do that, this code in the partial (which is expecting a local variable named pet) should work correctly:

<div>
  <strong>Name:</strong>
  <%= pet.name %>
</div>