【问题标题】:Rails 3 - Couldn't find <controller> without an IDRails 3 - 找不到没有 ID 的 <controller>
【发布时间】:2011-11-26 12:29:56
【问题描述】:

我创建了一个新控制器并添加了一个新操作 (my_new_action)。我在 routes.rb 中添加了此操作的路由,但是当我将地址设置为 URL 浏览器时,地址 localhost:3000/users/my_new_action,我将收到主题中的错误。

class UsersController < ApplicationController
  # ....

  def my_new_action  
  end
end

谁能帮帮我,怎么解决?

谢谢

编辑

  resources :users do
    collection do
      get 'my_new_action'
    end
  end

EDIT2 这是终端的确切输出:

    Started GET "/users/my_new_action" for 127.0.0.1 at Sat Nov 26 13:55:50 +0100 2011
  Processing by UsersController#my_new_action as HTML
filter_access_to tried to find User from params[:id] (nil), because attribute_check is enabled and @user isn't set, but failed: ActiveRecord::RecordNotFound: Couldn't find User without an ID
Completed 404 Not Found in 1ms

ActiveRecord::RecordNotFound (Couldn't find User without an ID):


Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.1.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.8ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.1.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.1ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.1.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (6.0ms)

【问题讨论】:

  • 我怀疑这就是您收到的确切错误消息 - 您能发布整个异常吗?
  • 您已经发布了确切的问题..."filter_access_to 尝试从 params[:id] (nil) 中查找用户,因为启用了属性检查并且未设置 @user,但失败:ActiveRecord ::RecordNotFound:找不到没有 ID 的用户”
  • 所以它是ActiveRecord::RecordNotFound (Couldn't find User without an ID)。您的 params[:id] 为 nil 并且 filter_access_to 找不到 id = nil 的用户...
  • 但是我想“my_new_action”页面只有一些文本信息,我该怎么做?我对此有点困惑
  • 所以解决问题的解决方案:filter_access_to :all, :except =&gt; : my_new_action

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


【解决方案1】:

标题具有误导性,您输入 &lt;controller&gt; 是因为您可能看到了 User,但它很可能是指您尝试构建或使用的模型。因为您没有粘贴更多代码,所以我无法确切说明问题出在哪里,但请查找对您在代码中使用的 id 的引用 - 这很可能是 null。

【讨论】:

  • 好吧,我的控制器中只有 empy 动作,只有动作的定义,我对此动作的视图也是空的。我希望这足以创建一个新操作...我不想使用对 ID 的引用...只是创建一个新的“页面”(+ 我更新了我的问题)
  • 在更新中你已经为你拼出了错误:filter_access_to tried to find User from params[:id] (nil), because attribute_check is enabled and @user isn't set, but failed: ActiveRecord::RecordNotFound: Couldn't find User without an ID
  • 但是怎么可能,如果我设置 url users/new,一切正常?
【解决方案2】:

您收到错误是因为路由不起作用,代码显示的是 URL /users/my_new_action 正在尝试为默认的“show”查找用户 ID“/users/my_new_action”行动。

我会将您提供的路线代码替换为类似的东西(请不要这是未经测试的代码)...

resources :users do
    match '/my_new_action', :controller => 'users', :action => 'my_new_action', :as => :mynewaction
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多