【问题标题】:Why am I seeing "No route matches :action=>"show"" when my show action is defined for that controller?当我为该控制器定义显示操作时,为什么我会看到“没有路由匹配:action=>“show””?
【发布时间】:2012-11-12 16:38:51
【问题描述】:

我有一个“类别”资源,并且正在尝试使用 link_to 方法和 _path 路由在其 index.html.erb 文件中链接到 Categories#show。当我在浏览器中查看索引时,我看到以下错误:

Routing Error No route matches {:action=>"show", :controller=>"categories"}

但我确实在我的 Categories 控制器中定义了一个显示操作,并且删除 link_to 的 URI 部分会导致索引正常显示而不会引发异常!我不知道URI哪里出错了。

这里是 /categories/index.html.erb:

<h1>My Links</h1>

<% @categories.each do |c| %>
    <h2><%= link_to "#{c.category}", category_path %></h2>
    <p><%= c.description %></p>
<% end %>

<%= link_to "Add new category", new_category_path %>

这里是 /categories/show.html.erb:

<h1><%= @category.category %></h1>

<p><%= @category.description %></p>

<p><%= link_to "Back to index", root_path %></p>

这里是 /config/routes.rb:

LinkManager::Application.routes.draw do

  resources :categories do
    resources :links
  end

  root :to => 'categories#index'

这是 /controllers/categories_controller.rb 的一部分:

class CategoriesController < ApplicationController

    def index
        respond_with(@categories = Category.all)
    end


    def show
        @category = Category.find(params[:id])
    end

这是运行rake routes 的结果(把它放在pastebin 上,因为我不知道如何在这里很好地格式化它):rake routes

谁能发现哪里出了问题?我在这里查看了许多其他类似的路由问题,但无法从他们那里得到解决方案。谢谢。

【问题讨论】:

  • 这是什么意思?我是堆栈溢出的新手。
  • 您提出了 5 个问题,但您没有接受其中任何一个问题,如果之前的任何问题找到了一个好的答案,您应该返回并接受它们(单击点下方的勾号)
  • 谢谢,已修复!我不知道。

标签: ruby-on-rails rails-routing


【解决方案1】:

尝试替换:

<h2><%= link_to "#{c.category}", category_path %></h2>

与:

<h2><%= link_to "#{c.category}", category_path(c) %></h2>

看到了吗?您必须为category_path 提供一个类别。

或者只是使用魔法:

<h2><%= link_to "#{c.category}", c %></h2>

顺便问一下,这里插值的目的是什么:"#{c.category}"?简单的c.category 还不够吗?

【讨论】:

  • 这行得通!我没有意识到 category_path 需要那个特定的参数。谢谢!
  • @hlh 你可以用一个整数代替(它将被视为id)。但是当你放置一个类别时,Rails 足够聪明地为你提取它的id
【解决方案2】:

好吧,我认为如果您添加其他路线以显示它有效,请执行以下操作:

在您的浏览器中执行此操作:

localhost:3000/categories/show

在你的routes.rb:

match "/categories/show/:id" => categories#show

我们的ruby版本和rails版本是多少?

【讨论】:

  • 如果您有任何问题,您应该将其发布在评论中,而不是您的答案中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-21
  • 2011-08-26
  • 2012-07-17
  • 2011-12-25
  • 1970-01-01
相关资源
最近更新 更多