cinameng
cinameng

Reputation: 323

Rails many to many relations with has many through relationships

I have the following models using the has_many :through relationship.

A recipe can have many seasons. A season can have many recipes.

Recipe

class Recipe < ApplicationRecord
  attribute :name

  has_many :recipe_seasons
  has_many :seasons, through: :recipe_seasons
end

Season

class Season < ApplicationRecord
    has_many :recipe_seasons
    has_many :recipes, through: :recipe_seasons
end

Recipe Season

class RecipeSeason < ApplicationRecord
  belongs_to :recipe
  belongs_to :season
end

I'm currently displaying all recipes on the index page using the the following

Controller

  def index
    @recipes = Recipe.all
    render index: @recipes, include: [:recipe_seasons, :seasons]
  end

View

 <% if @recipes.present? %>
   <% @recipes.each do |recipe| %>
     <%= link_to recipe.name,[recipe] %>
 <% end %>

What I want to do is to have the seasons displayed with the each recipe. A recipe can have more than one season and so I added another for loop inside the existing one for recipes.

I have so far tried:

<% @recipes.each do |recipe| %>
  <% recipe.seasons.each do |season| %>
    <%= link_to recipe.name,[recipe] %>
      <%= season.name %>
    <% end %>
  <% end %>
<% end %>

Current Behaviour

Recipe 1 - Season 1

Recipe 1 - Season 2

Expected Behaviour

Recipe 1 - Season 1, Season 2

Recipe 2 - Season 4

Upvotes: 0

Views: 34

Answers (1)

Baldrick
Baldrick

Reputation: 24350

You must include the seasons in the body parameter of the link_to (the text displayed in the link)

<% @recipes.each do |recipe| %>
   <%= link_to "#{recipe.name} - #{recipe.seasons.map(&:name).join(', ')}", [recipe] %>
<% end %>

Upvotes: 1

Related Questions