2011-03-07 35 views
0

我已經看到了這個問題,在這裏回答爲Rails 2,而不是Rails的3Rails 3中無法找到自定義動作

我有我在本地主機上運行的應用程序稱爲天網,它提供單點擊進入,我經常使用的腳本:

我:

的config/routes.rb文件:

Skynet::Application.routes.draw do 
    resources :robots do 
    member do 
     get "cleaner" 
    end 
    end 
end 

應用程序/控制器/ robots_controller.rb:

class RobotsController < ApplicationController 
    def index 
    respond_to do |format| 
     format.html 
    end 
    end 
    def cleaner 
    @output = '' 
    f = File.open("/Users/steven/Code/skynet/public/input/input.txt", "r") 
    f.each_line do |line| 
     @output += line 
    end 
    output = Sanitize.clean(@output, :elements => ['title', 'h1', 'h2', 'h3', 'h4', 'p', 'td', 'li'], :attributes => {:all => ['class']}, :remove_contents => ['script']) 
    newfile = File.new("/Users/steven/Code/skynet/public/output/result.txt", "w") 
    newfile.write(output) 
    newfile.close 
    redirect_to :action => "index" 
    end 
end 

(稍後將重構)

在應用程序/視圖/機器人/ I index.html.haml有:

= link_to "test", cleaner_robot_path 

當我鍵入耙路線,我得到:

cleaner_robot GET /robots/:id/cleaner(.:format) {:controller=>"robots", :action=>"cleaner"} 

那麼,爲什麼當我將瀏覽器指向http://localhost:3000/時,我會得到以下結果嗎?

ActionController::RoutingError in Robots#index 

Showing /Users/steven/Code/skynet/app/views/robots/index.html.haml where line #1 raised: 

No route matches {:action=>"cleaner", :controller=>"robots"} 
Extracted source (around line #1): 

1: = link_to "test", cleaner_robot_path 
Rails.root: /Users/steven/Code/skynet 

Application Trace | Framework Trace | Full Trace 
app/views/robots/index.html.haml:1:in `_app_views_robots_index_html_haml___2129226934_2195069160_0' 
app/controllers/robots_controller.rb:4:in `index' 
Request 

Parameters: 

None 
Show session dump 

Show env dump 

Response 

Headers: 

None 

回答

2

你定義cleaner作爲資源robots的成員函數,這意味着你必須提供一個id,你可以在你的rake routes消息看/robots/:id/cleaner(.:format)

所以你的鏈接應該像

= link_to "test", cleaner_robot_path(some_id) 

但是

我想你想要你清潔劑本身作爲一個集合函數:

Skynet::Application.routes.draw do 
    resources :robots do 
    collection do 
     get "cleaner" 
    end 
    end 
end 

那麼你的鏈接有看起來像:

= link_to "test", cleaner_robots_path 

注意,機器人現在是複數!

根據你的錯誤消息,我想你已經試過了,但用於複數集合......也許你有,如果你是在生產模式,以重新啓動服務器。

你可以閱讀更多有關Ruby on Rails Guide

+0

此路由東西工作了魅力。你猜對了。 :-) – 2011-03-07 10:39:05

相關問題