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

Rails路由问题:link_to跳转URL显示id而非实际ID值求助

点击link_to链接时,页面跳转到http://localhost:3000/categories/id,而非正确的http://localhost:3000/categories/1,手动在URL中输入真实ID可正常访问目标页面。以下是相关代码:

路由配置

resources :categories, only: [ :index, :show ] do
  resources :stocks, only: [ :index, :show ]
end

resources :stocks, only: [ :index, :show ] do
  resources :histories, only: [ :index ]
end
<% @categories.each do |c| %>
  <%= link_to category_path(:id) do %>
    <%= c.name %>
  <% end %>

Categories控制器代码

def index
  @categories = Category.all
  @stocks = Stock.all
end

def show
  @category = Category.find(params[:id])
  @stock = Stock.find(params[:id])
  @categories = Category.where(id: @stocks)
  @stocks = Stock.where(category_id: @stock.id)
end

问题根源

你的link_to调用里,category_path(:id)是把符号:id作为参数直接传入,Rails会把这个符号解析成字符串"id",所以生成的URL是/categories/id,而不是动态获取当前分类的ID。

修复方案

修改link_to中的路由辅助方法参数,直接传入循环中的分类对象c(Rails会自动提取对象的id属性),或者明确传入c.id:

<% @categories.each do |c| %>
  <%= link_to category_path(c) do %>
    <%= c.name %>
  <% end %>

或者:

<% @categories.each do |c| %>
  <%= link_to category_path(c.id) do %>
    <%= c.name %>
  <% end %>

额外注意:Categories控制器show方法的逻辑错误

你的show方法里存在明显的逻辑问题:

  1. @stock = Stock.find(params[:id]):用分类的ID去查询Stock,会导致错误(除非分类ID和StockID刚好重合),完全不符合业务逻辑。
  2. @stocks = Stock.where(category_id: @stock.id):正确写法应该是基于当前分类的ID查询关联的Stock,即@stocks = @category.stocks(需在Category模型中定义has_many :stocks关联),或者Stock.where(category_id: @category.id)。
  3. @categories = Category.where(id: @stocks):这行逻辑混乱,@stocks是Stock集合,用它们的id去查Category毫无意义,建议删除。

修正后的show方法示例(假设Category和Stock是一对多关联):

def show
  @category = Category.find(params[:id])
  @stocks = @category.stocks # 依赖模型中定义的has_many :stocks关联
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:45:38