允许用户使用设备编辑自己的数据

时间:2013-05-13 15:09:27

标签: ruby-on-rails devise

我知道其他地方可能有解决方案,但我正在寻找专门针对我的情况的帮助,因为我在将其他解决方案转化为我的情况时遇到了很多麻烦。

我目前正在设置设备并且数据库已播种,因此已创建管理员。之后签名的其他人都是用户。

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

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

2 个答案:

答案 0 :(得分:1)

设计与身份验证(您是谁)相关,您需要一个授权解决方案(谁可以做什么)。我的建议是去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

这将允许用户只读取,创建,编辑和销毁用户ID匹配用户ID的学员。

看看CanCan github页面是否有很好的文档和很多例子;设置和工作非常简单。

答案 1 :(得分: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