0

菜鸟在这里。

试图弄清楚如何将控制器中的方法显示到我的索引页面中。这是我到目前为止所拥有的。

控制器 -

 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.

任何帮助将不胜感激。

谢谢!

4

1 回答 1

2

如果您查看您的路线,它也在:sammic_id那里:

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

这意味着您需要将一个 id 传递给您sammich_random_path没有的 URL 助手。

将您的路线更新为:

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

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

于 2013-05-03T00:36:16.103 回答