Reputation: 1594
Following on from this question
class CoffeeRoast < ApplicationRecord
has_many :coffee_blends
has_many :coffee_beans, through: :coffee_blends
has_one :country, through: :coffee_beans
end
class CoffeeBean < ApplicationRecord
has_many :coffee_blends
has_many :coffee_roasts, through: :coffee_blends
belongs_to :country
end
class Country < ApplicationRecord
has_many :coffee_beans
end
class CoffeeBlend < ApplicationRecord
belongs_to :coffee_bean
belongs_to :coffee_roast
end
I am able to show the related coffee_beans
on the coffee_roasts
show page, and also the country
, however, I can not work out how to display them correctly.
My current code is attempting to show the bean and its related country on the same row on the table, however the top is blank and the two countries are both in the second row.
coffee_roasts/show.html.erb
<h1 class="display-3"><%= @coffee_roast.name %></h1>
<p>
by <h2 class="display-6"><%= @coffee_roast.roaster.roaster_name %></h2>
</p>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Bean</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<% @coffee_roast.coffee_blends.each do |blend| %>
<tr>
<th><%= blend.coffee_bean.name %>
<% end %></th>
<th><%= @coffee_roast.coffee_beans.map {|cb| cb.country.country_name }.join(', ') %></th>
</tr>
</tbody>
</table>
Finca La Cumbre | El Salvador, Guatemala
El Salvador
show be in-line with the El Martillo
bean.
My approach feels quite wrong here, but I'm pretty new to working with multiple levels of models so still learning.
How can I get the beans associated country to display alongside the bean?
Upvotes: 0
Views: 22
Reputation: 1594
This was actually a lot simpler than I thought. I've found the below works perfectly. No need to map an array.
<tbody>
<% @coffee_roast.coffee_blends.each do |blend| %>
<tr>
<td><%= blend.coffee_bean.name %></td>
<td><%= blend.coffee_bean.country.country_name %></td> #this bit was the original concern.
<td><%= blend.coffee_bean.variety %></td>
<td><%= blend.coffee_bean.process %></td>
<% end %>
</tr>
</tbody>
Upvotes: 1
Reputation: 161
<tbody>
<% @coffee_roast.coffee_blends.each do |blend| %>
<tr>
<td><%= blend.coffee_bean.name %></td>
<td><%= @coffee_roast.coffee_beans.map {|cb| cb.country.country_name }.join(', ') %></td>
</tr>
<% end %>
</tbody>
try and see if this works?
Upvotes: 0