首页 > 解决方案 > Rails 调用已删除的控制器

问题描述

这里的基本 Rails 问题:我有一个名为的控制器方法fetch_headlines,我一直在尝试调试。我对控制器进行了更改,但它们没有反映在输出中。这让我觉得 Rails 没有正确调用fetch_headlines. 观察下面的控制台。

Puma starting in single mode...
* Version 3.12.1 (ruby 2.6.1-p33), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop
Started GET "/entries/fetch_headlines" for ::1 at 2020-01-08 16:03:03 -0500
   (0.6ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
  ↳ /Users/ed/.rvm/gems/ruby-2.6.1/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Processing by EntriesController#show as HTML
  Parameters: {"id"=>"fetch_headlines"}
  Rendering entries/show.html.erb within layouts/application
  Rendered entries/show.html.erb within layouts/application (2.8ms)
Completed 200 OK in 482ms (Views: 476.3ms | ActiveRecord: 0.0ms)

此外,如果我请求不存在的方法,Rails 会呈现相同的行为,例如:qwertyqwerty. 我希望 Rails 会抛出错误。

Started GET "/entries/qwertyqwerty" for ::1 at 2020-01-09 05:59:13 -0500
Processing by EntriesController#show as HTML
  Parameters: {"id"=>"qwertyqwerty"}
  Rendering entries/show.html.erb within layouts/application
  Rendered entries/show.html.erb within layouts/application (0.6ms)
Completed 200 OK in 18ms (Views: 17.1ms | ActiveRecord: 0.0ms)

这是我的路线.rb

get 'fetch_headlines', to: 'entries#fetch_headlines'
  resources :entries
  resources :keywords
  resources :networks

谢谢。

标签: ruby-on-railsruby

解决方案


你放get 'fetch_headlines', to: 'entries#fetch_headlines',它创建/fetch_headlines而不是/entries/fetch_headlines路由。你需要的是这样的:

get 'entries/fetch_headlines', to 'entries#fetch_headlines'

甚至更好

resources :entries do
  collection do
    get :fetch_headlines
  end
end

推荐阅读