【问题标题】:Rails 3 can't find a custom actionRails 3 找不到自定义操作
【发布时间】:2011-03-07 10:23:58
【问题描述】:

我在 Rails 2 看到了这个问题的答案,但 Rails 3 没有。

我在本地主机上运行了一个名为 Skynet 的应用程序,它提供对我经常使用的脚本的一键访问:

我有:

config/routes.rb:

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

app/controllers/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

(稍后会重构。)

在 app/views/robots/index.html.haml 我有:

= link_to "test", cleaner_robot_path

当我输入 rake routes 时,我得到:

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    您将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
    

    注意,robot 现在是复数形式了!

    根据您的错误消息,我猜您已经尝试过了,但使用了复数形式的集合...如果您处于生产模式,也许您必须重新启动服务器。

    您可以在Ruby on Rails Guide 中阅读有关此路由的更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 2012-03-31
      • 2012-06-19
      相关资源
      最近更新 更多