路由问题。找不到路线,但我知道这些路线存在

时间:2013-05-03 00:29:23

标签: ruby-on-rails ruby routing routes

Noob在这里。

试图找出如何在控制器中将方法显示到索引页面中。这是我到目前为止所做的。

控制器 -

 class SammichesController < ApplicationController
  def index
    @sammiches = Sammich.all
end
  def create
    @sammich = Sammich.find_by_name(params[:sammich][:name])
  end
  def random
    @sammichy = Sammich.rand(params[:sammich][:name])
  end
end

路线 -

Sammiches::Application.routes.draw do
resources :sammiches do
  get "random"
end
root :to => 'sammiches#index'

索引 -

<h1>All my Sammiches</h1>
<%= form_for Sammich.new do |f| %>
<%= f.label :sammich %>
<%= f.text_field :name %>
<%= f.submit 'Find Sammich', :id => 'sammich_submit' %>
<% end %>
<%= link_to "Random sandwich", sammich_random_path %>

路线 -

sammich_random GET    /sammiches/:sammich_id/random(.:format) sammiches#random
     sammiches GET    /sammiches(.:format)                    sammiches#index
               POST   /sammiches(.:format)                    sammiches#create
   new_sammich GET    /sammiches/new(.:format)                sammiches#new
  edit_sammich GET    /sammiches/:id/edit(.:format)           sammiches#edit
       sammich GET    /sammiches/:id(.:format)                sammiches#show
               PUT    /sammiches/:id(.:format)                sammiches#update
               DELETE /sammiches/:id(.:format)                sammiches#destroy
          root        /                                       sammiches#index

错误 -

localhost:3000 - Routing Error

No route matches {:action=>"random", :controller=>"sammiches"}
Try running rake routes for more information on available routes.

非常感谢任何帮助。

谢谢!

1 个答案:

答案 0 :(得分:2)

如果你看一下你的路线,那里也有:sammic_id

sammich_random GET    /sammiches/:sammich_id/random(.:format) sammiches#random

这意味着您需要将ID传递给您尚未拥有的网址助手sammich_random_path

更新您的路线:

resources :sammiches do
  collection do
    get "random"
  end
end

添加后,您的路线将只是/sammiches/random