gpt4 book ai didi

ruby-on-rails - 用户 Controller 渲染错误 : NoMethodError in Users#show 中的 before_action

转载 作者:行者123 更新时间:2023-12-04 04:39:08 27 4
gpt4 key购买 nike

我正在关注 Michael Hartl 的 Rails 指南(第 9 章)。当我尝试访问与用户个人资料对应的页面时,浏览器显示以下错误消息:

 NoMethodError in Users#show

Showing /home/jonathan/Desktop/railsTut/sample_app/app/views/users/show.html.erb where line #1 raised:

undefined method `name' for nil:NilClass

Extracted source (around line #1):

1: <% provide(:title, @user.name) %>
2: <div class="row">
3: <aside class="span4">
4: <section>

Rails.root: /home/jonathan/Desktop/railsTut/sample_app

这是我的 users_controller.rb
class UsersController < ApplicationController
before_action :signed_in_user, only: [:edit, :update]

def show
@user = User.find(params[:id])
end

def new
@user = User.new
end

def create
@user = User.new(params[:user]) # Not the final implementation!
if @user.save
sign_in @user
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end

def edit
@user = User.find(params[:id])
end

def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
flash[:success] = "Profile updated"
sign_in @user
redirect_to @user
else
render 'edit'
end
end

def destroy
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_url
end

private

def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end


# Before filters

def signed_in_user
unless signed_in?
store_location
redirect_to signin_url, notice: "Please sign in."
end
end
end

页面加载正常,没有该行:
before_action :signed_in_user, only: [:edit, :update]

但是随着它的包含,事情出错了,我不知道为什么。

另外,这里是 routes.rb
SampleApp::Application.routes.draw do
resources :users
resources :sessions, only: [:new, :create, :destroy]

root to: 'static_pages#home'

match '/signup', to: 'users#new'
match '/signin', to: 'sessions#new'
match '/signout', to: 'sessions#destroy', via: :delete

match '/help', to: 'static_pages#help'
match '/about', to: 'static_pages#about'
match '/contact', to: 'static_pages#contact'

end

任何帮助表示赞赏!

最佳答案

而不是 行动前用户_ Controller 先试后过滤
所以你的代码看起来像这样:

before_filter :signed_in_user, only: [:edit, :update]

我有完全相同的错误!

关于ruby-on-rails - 用户 Controller 渲染错误 : NoMethodError in Users#show 中的 before_action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17807475/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com