You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails路由与link_to问题:从Sets列表页跳转至Cards列表页

解决方案

第一步:修复视图链接错误

当前路由报错的直接原因是循环中误用了未定义的@pokemon_set变量,循环内的集合对象是set,修改链接参数即可解决:

<h1>Pokemon Sets</h1>

<ul>
  <% @pokemon_sets.each do |set| %>
    <li><%= link_to(set.name, pokemon_set_pokemon_cards_path(set)) %></li> <!-- 将@pokemon_set替换为set -->
    <li><%= set.series %></li>
    <li><%= image_tag(set.image_url, size: "250x150") %></li>
  <% end %>
</ul>

第二步:修正数据库关联关系(核心问题)

你当前的Schema外键逻辑完全颠倒:一个Pokemon Set对应多张Pokemon Card是一对多关联,外键应放在子表pokemon_cards中,而非父表pokemon_sets。

  1. 生成迁移添加正确外键:
rails generate migration AddPokemonSetIdToPokemonCards pokemon_set_id:integer
rails db:migrate
  1. 清理冗余的错误外键(可选但建议执行):
rails generate migration RemoveCardIdFromPokemonSets card_id:integer
rails db:migrate
  1. 配置模型关联:
    app/models/pokemon_set.rb:
class PokemonSet < ApplicationRecord
  has_many :pokemon_cards, dependent: :destroy
end

app/models/pokemon_card.rb:

class PokemonCard < ApplicationRecord
  belongs_to :pokemon_set
end

第三步:完善卡片控制器逻辑

确保PokemonCardsController能正确获取对应集合下的卡片:

class PokemonCardsController < ApplicationController
  before_action :find_pokemon_set

  def index
    @pokemon_cards = @pokemon_set.pokemon_cards
  end

  def show
    @pokemon_card = @pokemon_set.pokemon_cards.find(params[:id])
  end

  private

  def find_pokemon_set
    @pokemon_set = PokemonSet.find(params[:pokemon_set_id])
  end
end

完成以上修改后,点击集合名称即可直接跳转到对应卡片列表页,路由与关联逻辑都能正常工作。

内容的提问来源于stack exchange,提问作者mustafaalomer711

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:31:15