2011-03-07 44 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