【发布时间】:2016-03-12 14:23:42
【问题描述】:
我想检查当前对象的用户id是否与当前用户的id相同,所以我可以只允许登录用户进行一些操作。我正在使用 Devise gem 来帮助我进行身份验证。
也就是说,我想问一个范围更广的问题。我已经建立了关联,至少我是这么认为的,但是当我在浏览器中打开相应页面时出现错误:
undefined method 'user' for nil:NilClass
我知道当数据库中的特定对象未实例化或没有条目时,通常会发生此错误,但我使用控制台和 PostgreSQL GUI 工具来检查数据是否存在。
首先澄清一下我的理解是对的,下面是一些事情的作用:
- 如果您在控制器的“私有”部分中定义方法 (def x),这意味着数据仅在您的控制器中可用?
- 通过回调 (before_action),您可以使用私有方法的数据填充应用的 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
在我使用的对应图像控制器中:
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 字段已填充,所以我不知道为什么会出现此错误。也许我忘记了什么?
【问题讨论】:
标签: ruby-on-rails ruby postgresql devise