2013-05-13 39 views
0

我知道在其他地方可能有解决方案,但我在寻求专门针对我的情况的帮助,因为我在将其他解决方案转换为我的情况时遇到了很多麻烦。允许用户使用设备编辑他们自己的数据

我目前有一个设备设置和数据库播种,所以管理已经创建。在此之后注册的其他人都是用户。

现在有两个表,一个由rails和cadet表生成的用户表。学员表存储诸如companyroom number,class year等的信息。

我的问题是,我如何让用户只编辑/销毁他们创建的学员记录?我知道这似乎是一个很大的问题,但我一直在寻找,仍然无法找到一个合理的方式来实现这一点。谢谢!

回答

1

设计与认证(你是谁)有关,你需要一个授权解决方案(谁可以做什么)。我的建议是去CanCan(https://github.com/ryanb/cancan),这是一个广泛使用的广泛设计的宝石。

对于你的榜样,并安装通过的Gemfile +捆扎机宝石后:

初始化宝石为您的用户模型

rails g cancan: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。

看看CanCan github页面是否有很好的文档记录和大量的例子;设置起来非常简单,而且效果很好。

1

你也可以使用一个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 

end 
相关问题