我知道其他地方可能有解决方案,但我正在寻找特别适用于我的情况的帮助,因为我在将其他解决方案转换为我的情况时遇到了很多麻烦。
我目前有一个设备设置和数据库是种子,所以已经创建了一个管理员。在此之后注册的其他所有人都是用户。
现在有两个表,一个是由rails生成的用户表,另一个是学员表。学员表存储诸如company、room number、class year等信息。
我的问题是,如何允许用户仅编辑/销毁他们创建的学员记录?我知道这似乎是一个很大的问题,但我一直在寻找,仍然找不到一个合理的方法来实现这一点。谢谢!
发布于 2013-05-13 23:20:10
设计与身份验证(您是谁)相关,您需要一个授权解决方案(谁可以做什么)。我的建议是去CanCan (https://github.com/ryanb/cancan),这是一个非常广泛使用的宝石广泛的设计。
对于您的示例,在通过Gemfile+Bundler安装gem之后:
为您的用户模型初始化gem
rails g cancan:ability它将在app/models/ability.rb中创建一个文件来定义您的限制
定义您的限制,例如:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (this line it to manage users not logged in yet)
if user
can :manage, Cadet, user_id: user.id
end
end
end这将允许用户只读取、创建、编辑和销毁user_id与用户id匹配的学员。
看看CanCan的github页面,它有很好的文档记录,有很多例子;它设置起来很简单,而且效果很好。
发布于 2013-05-13 23:37:42
您还可以使用before_filter,如下所示:
class CadetsController < ApplicationController
before_filter :cadet_belongs_to_user, only: [:show, :edit, :update, :destroy]
....
private
def cadet_belongs_to_user
# following will work only on routes with an ID param
# but there are a few ways you could check if the cadet
# belongs to the current user
unless current_user && current_user.cadets.where(id: params[:id]).any?
flash[:notice] = "You are not authorized to view this page."
redirect_to root_path
end
end
endhttps://stackoverflow.com/questions/16525371
复制相似问题