我正在尝试为每个用户创建一个展示页面作为个人资料页面。但是,我一直在使用未定义的方法`username' for nil:当我尝试在视图中显示任何内容时,NilClass为错误消息。
我使用Devise来注册和存储用户信息。我的用户被称为"艺术家"。
/routes.rb
devise_for :artists, controllers: { sessions: "artists/sessions", passwords: "artists/passwords", registrations: "artists/registrations", confirmations: "artists/confirmations", unlocks: "artists/unlocks"}
resources :artists, only: [:show, :index]
/artists_controller.rb
class ArtistsController < ApplicationController
def show
@artist = Artist.find(params[:id])
end
end
/show.html.erb
<%= @artist.username %>
如果我尝试显示电子邮件,ID等,我会收到此错误
日志
Started GET "/artists/1" for 127.0.0.1 at 2015-01-04 14:00:47 -0500
Processing by ArtistsController#show as HTML
Parameters: {"id"=>"1"}
Rendered artists/show.html.erb within layouts/application (5.0ms)
Completed 500 Internal Server Error in 24ms
ActionView::Template::Error (undefined method `username' for nil:NilClass):
1: <div>
2: <%= @artist.username %>
3: </div>
4: <div>
5: <ul>
app/views/artists/show.html.erb:2:in `_app_views_artists_show_html_erb___67732
1755_70508328'
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.1.8
/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (7.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.1.8
/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
(4.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.1.8
/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within
rescues/layout (91.0ms)
答案 0 :(得分:0)
如果您将ArtistsController
嵌套到/artists
中,要使路线正常工作,您需要使用
get 'artists/:id' => 'artists/artists#show', as: :artist
或
resources :artists, controller: 'artists/artists', only: [:show]