获取 "The action 'show' could not be found" 即使我已经在我的 config/routes.rb 文件中定义了方法

Getting "The action 'show' could not be found" even though I have defined the method in my config/routes.rb file

我正在使用 Rails 4.2.3。我的 config/routes.rb 文件中有这个

resources :my_objects do
  get "import"
end

并在我的 app/controllers/my_objects_controller.rb 文件中定义了它

def import
  puts "starting"
  service = XACTEService.new(“Stuff”, '2015-06-01', 'Zoo')
  service.process_my_object_data
  puts "finished"
end

当我访问 http://localhost:3000/my_objects/import 时,出现此错误:

The action 'show' could not be found for MyObjectsController” error.

我在日志文件中没有看到来自我的 import 操作的“puts”语句。我还需要做什么才能调用 import 方法?

import 路由名称被视为 show 的参数,因为路由未正确定义。检查 rake routes 的输出,看看它在这种情况下实际做了什么。

相反,您需要像这样定义路线:

resources :my_objects do
  collection do
    get "import"
  end
end

或者像这样:

resources :my_objects do
  member do
    get "import"
  end
end

Rails Routing from the Outside In guide has a section called Adding More RESTful Actions 将帮助您确定哪些选项适合您的应用。