0

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

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

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

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

4

2 回答 2

1

您还可以使用 a 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
于 2013-05-13T15:37:41.507 回答
1

设计与身份验证(你是谁)有关,你需要一个授权解决方案(谁可以做什么)。我的建议是选择 CanCan ( https://github.com/ryanb/cancan ),这是一个非常广泛使用的 gem。

对于您的示例,在通过 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 匹配的 Cadets。

看看 CanCan 的 github 页面,文档很好,有很多例子;设置非常简单,效果很好。

于 2013-05-13T15:20:09.843 回答