gpt4 book ai didi

ruby-on-rails - 如何避免未定义方法错误

转载 作者:行者123 更新时间:2023-11-29 13:54:56 26 4
gpt4 key购买 nike

我想检查当前对象的用户 ID 是否与当前用户的 ID 相同,因此我可以只允许登录用户执行某些操作。我正在使用 Devise gem 来帮助我进行身份验证。

也就是说,我想问一个范围更广的问题。我建立了关联,至少我是这么认为的,但是当我在浏览器中打开相应的页面时,我得到了错误:

undefined method 'user' for nil:NilClass

我知道当数据库中的特定对象未实例化或没有条目时经常会发生此错误,但我正在使用控制台和 PostgreSQL GUI 工具来检查数据是否存在。

这是截图https://www.evernote.com/shard/s233/sh/305c5194-87e0-4019-9eba-9a7f5d7a2839/7c89b4842cc6efc1/res/b7879832-7829-4fe3-b81a-386b6f81cc11/skitch.png?resizeSmall&width=832

首先澄清一下,我的理解是正确的,下面是一些事情的作用:

  1. 如果您在 Controller 的“私有(private)”部分中定义方法 (def x),这意味着数据仅在您的 Controller 中可用?
  2. 通过回调(before_action),您可以使用私有(private)方法的数据填充应用的 REST 方法,它可能想要使用?

现在我有一个图像模型:

class Image < ActiveRecord::Base
mount_uploader :image, ImageUploader
belongs_to :user
belongs_to :game, inverse_of: :images
end

用户模型是这样的:

class User < ActiveRecord::Base
...
has_many :images
has_many :games
validates :first_name, :last_name, presence: true
end

在我使用的相应图像 Controller 中:

class ImagesController < ApplicationController
before_action :set_image, only: [:show, :edit, :update, :destroy]
before_action :set_game
before_action :authenticate_user!
before_action :check_user
...
private

def set_image
@image = Image.find(params[:id])
end

def set_game
@game = Game.all
end

def check_user
unless (@image.user == current_user) || (current_user.admin?)
redirect_to root_url, alert: "Sorry but you are not allowed to visit this page."
end
end

def image_params
params.require(:image).permit(:title, :alt, :desc, :image, :category)
end
end

check_user 方法中使用 @image.user 我尝试获取用户的 ID。如果我只使用 current_user.admin? 它可以工作,但显然不是预期的那样。

如您在上面的屏幕截图中所见,user_id 字段已填充,所以我不知道为什么会出现此错误。也许我忘记了什么?

最佳答案

根据您的错误消息,问题出在 check_user 方法中的 @image.user 上。这里,@imagenil。您应该检查 @image.nil? 是否在那里。

大概改成:

@image = Image.find(params[:id])
unless !@image.nil? && ((@image.user == current_user) || (current_user.admin?))

顺便说一句,您应该只在 :show, :edit, :update, :destroy 中检查用户,例如:

before_action :check_user, only: [:show, :edit, :update, :destroy]

关于ruby-on-rails - 如何避免未定义方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34142787/

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