开发者

No Method error in UsersController

I began coding in Rails several weeks ago, and I can't figure out why I have this error. I'm using Devise for log-ins and Formtastic for forms. The app was working correctly until I added the Acts_like_tags_on and reset the database.

The error message: NoMethodError in UsersController#show

undefined method `username' for nil:NilClass

app/controllers/users_controller.rb:19:in `show'
Request

Parameters:
{"id"=>"sign_in"}

This is what I have in the Users C开发者_开发技巧ontroller:

def show
 @user = User.find_by_username(params[:id])
 @title = @user.username

 respond_to do |format|
   format.html # show.html.erb
   format.json { render json: @user }
 end
end

Any input would be helpful. Thanks!

After editing @user = User.find_by_username(params[:id]) to: @user = User.find_by_user(params[:id])

The error becomes: undefined method `find_by_user' for #

The username column does exist in the User table.


@user = User.find_by_username(params[:id])

That line above may be returning nil. If you do User.find_by_username("Superman-is-awesome") and that username does not exist in your database, it's going to return nil.

Then it is trying to do:

@title = @user.username

Which is essentially:

@title = nil.username

Which of course won't work. So could be something wrong with the parameter you are passing in.

Also, make sure your User table have a column called 'username'? Make sure you've run:

rake db:migrate

As well.


If you configured the routes correctly, you should have devise routes BEFORE user resource, like this:

devise_for :users
resources :users, except: "create"


This is actually a routing problem

The problem is that devise expects you to have a route that will turn:

"/users/sign_in" into sessions#new

but your routes file is missing that route, and so the dispatcher is matching against the:

"users/:id" route which then goes to: users#show with :id => 'sign_in'

(and hence throws an error when it tries to find a user with the id of "sign_in")

You need to read the README doc for devise (google if you don't have it locally) - especially the part that describes how to add the standard set of routes to config/routes.rb Then do whatever it says. :)

Should be right after that.


I found that the user_id was being given the value of 'users'. After commenting the following line out in my routes.rb, the id was no longer given that value.

match '/:id' => 'users#show', :as => :user

I also needed the users_controllers #show to have the following line, since my user path uses the username. removing '_by_username' caused an error on pages that called for the username:

@user = User.find_by_username(params[:id])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜