【问题标题】:Why params[:id] is nil?为什么 params[:id] 为零?
【发布时间】:2013-05-06 11:22:22
【问题描述】:

我试图创建关注/取消关注按钮,但我的索引操作出现错误:

找不到没有 ID 的用户

users_controller.rb:

class UsersController < ApplicationController
  before_filter :authenticate_user!
  def index
    @user = User.find(params[:id])
  end
end

我发现params[:id]nil。我对 Rails 很陌生,我不明白为什么是nil

谁能解释我做错了什么?

【问题讨论】:

  • 您是否在请求中添加了 'id' 参数?
  • 你使用了 /users/put_id_here 类型的 url

标签: ruby-on-rails twitter-follow


【解决方案1】:

如果您运行rake routes,您将看到哪些路由采用id,哪些不采用,示例输出:

GET     /photos             index   
GET     /photos/new         new
POST    /photos create      create
GET     /photos/:id         show
GET     /photos/:id/edit    edit
PUT     /photos/:id         update
DELETE  /photos/:id         destroy

所以在上面只有showeditupdatedestroy 路由可以采用id

除非您更改了路线,否则index 通常用于集合,因此:

def index
  @users = User.all # no id used here, retreiving all users instead
end

当然你可以随意配置路由,例如:

get "users/this-is-my-special-route/:id", to: "users#index"

现在localhost:3000/users/this-is-my-special-route/12 将调用用户index 操作。尽管在这种情况下,您最好创建与其对应的新路由和操作,而不是像那样更改索引。

您可以在routing in Rails here 上阅读更多内容。

【讨论】:

  • 现在说得通了。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2017-10-13
  • 2019-11-22
  • 1970-01-01
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多