注册和登录时,nil的未定义方法`username’:NilClass
每当我尝试登录并注册时,我都会遇到此错误:
nil的未定义方法`username’:NilClass
在这两行:
以下是服务器输出的完整错误:
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."username" = 'sign_in' LIMIT 1 Rendered users/show.html.erb within layouts/application (2.1ms) Completed 500 Internal Server Error in 7ms ActionView::Template::Error (undefined method `username' for nil:NilClass): 1:
2: 3: 4: app/views/users/show.html.erb:1:in `_app_views_users_show_html_erb__1133891108745893964_2164088020'
这是我的路线:
Stynyl::Application.routes.draw do resources :things resources :users, only: [:show] devise_for :users get '/about', to: 'pages#about' root 'things#index' end
这是我的用户显示视图
By Edit Delete
这是我的UsersController文件:
class UsersController < ApplicationController def show @user = User.find_by_username(params[:id]) end end
耙路线的输出:
Prefix Verb URI Pattern Controller#Action things GET /things(.:format) things#index POST /things(.:format) things#create new_thing GET /things/new(.:format) things#new edit_thing GET /things/:id/edit(.:format) things#edit thing GET /things/:id(.:format) things#show PATCH /things/:id(.:format) things#update PUT /things/:id(.:format) things#update DELETE /things/:id(.:format) things#destroy users POST /users(.:format) users#create new_user GET /users/new(.:format) users#new user GET /users/:id(.:format) users#show new_user_session GET /users/sign_in(.:format) devise/sessions#new user_session POST /users/sign_in(.:format) devise/sessions#create destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy user_password POST /users/password(.:format) devise/passwords#create new_user_password GET /users/password/new(.:format) devise/passwords#new edit_user_password GET /users/password/edit(.:format) devise/passwords#edit PATCH /users/password(.:format) devise/passwords#update PUT /users/password(.:format) devise/passwords#update cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel user_registration POST /users(.:format) devise/registrations#create new_user_registration GET /users/sign_up(.:format) devise/registrations#new edit_user_registration GET /users/edit(.:format) devise/registrations#edit PATCH /users(.:format) devise/registrations#update PUT /users(.:format) devise/registrations#update DELETE /users(.:format) devise/registrations#destroy about GET /about(.:format) pages#about root GET / things#index
编辑
- 我还注意到,当我从User show视图中删除所有代码时,我可以访问注册和登录页面,但它们是空白的 。 我们能否安全地保证问题出在视图中? 我很惊讶于节目视图中的某些内容会影响登录和注册的能力!
- 我还观察到,当我向用户显示视图添加内容时,它会出现在注册和登录页面上。 到底是怎么回事?
原因是您的路线发生冲突。 将请求与路由匹配时,Rails将按顺序遍历您的路由。 但是您的订单显示:
user GET /users/:id(.:format) users#show new_user_session GET /users/sign_in(.:format) devise/sessions#new
所以Rails将sign_in
作为:id
参数传递给用户show方法,而不是被new_user_session_path
的new_user_session_path
。 更改订单将解决问题。
TL:DR; devise_for :users
应在 resources :users
之前声明resources :users
。