ruby-on-railstwitter-follow

Why params[:id] is nil?


I was trying to create follow/unfollow button, but I have the error in my index action:

Couldn't find User without an ID

users_controller.rb:

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

I found out that params[:id] is nil. I'm very new to Rails and I can't understand why it is nil.

Can anyone explain what I'm doing wrong?


Solution

  • If you run rake routes you'll see which routes take an id and which don't, example output:

    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
    

    So in the above only the show, edit, update and destroy routes can take an id

    Unless you've changed your routes, index is usually used for a collection, so:

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

    Of course you can configure routes as you please, for example:

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

    Now localhost:3000/users/this-is-my-special-route/12 will invoke the users index action. Although in this case you're better off creating a new route and action that corresponds to it, rather than changing the index like that.

    You can read more on routing in Rails here.