英文:
Rails many to many relations with has many through relationships
问题
我有以下使用has_many :through关联的模型。
一个食谱可以有多个季节。
一个季节可以有多个食谱。
食谱
class Recipe < ApplicationRecord
attribute :name
has_many :recipe_seasons
has_many :seasons, through: :recipe_seasons
end
季节
class Season < ApplicationRecord
has_many :recipe_seasons
has_many :recipes, through: :recipe_seasons
end
食谱季节
class RecipeSeason < ApplicationRecord
belongs_to :recipe
belongs_to :season
end
我目前在索引页面上显示所有的食谱,使用以下代码:
控制器
def index
@recipes = Recipe.all
render index: @recipes, include: [:recipe_seasons, :seasons]
end
视图
<% if @recipes.present? %>
<% @recipes.each do |recipe| %>
<%= link_to recipe.name, [recipe] %>
<% end %>
<% end %>
我想要的是在每个食谱旁边显示季节。一个食谱可以有多个季节,所以我在现有的食谱循环内添加了另一个循环。
我尝试过以下代码:
<% @recipes.each do |recipe| %>
<% recipe.seasons.each do |season| %>
<%= link_to recipe.name, [recipe] %>
<%= season.name %>
<% end %>
<% end %>
当前行为
食谱1 - 季节1
食谱1 - 季节2
期望的行为
食谱1 - 季节1,季节2
食谱2 - 季节4
英文:
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
答案1
得分: 1
你必须在link_to
的body
参数中包含季节(链接中显示的文本)。
<% @recipes.each do |recipe| %>
<%= link_to "#{recipe.name} - #{recipe.seasons.map(&:name).join(', ')}", [recipe] %>
<% end %>
英文:
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 %>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论