Rails、Devise、Role Model 和 CanCanCan - 定义能力

Posted

技术标签:

【中文标题】Rails、Devise、Role Model 和 CanCanCan - 定义能力【英文标题】:Rails, Devise, Role Model and CanCanCan - defining abilities 【发布时间】:2015-11-25 02:51:27 【问题描述】:

我正在使用 Rails 4 制作一个网络应用程序。

我正在尝试使用 CanCanCan 来定义各种角色的能力。

我有一个 User 模型和一个 Profile 模型。每个用户可以有许多个人资料。每个配置文件都可以有不同的角色。

在我的 Profile.rb 中,我将我的角色(使用角色模型 gem)定义为:

  include RoleModel

roles :admin, :manager, # coalfacer
        :student, :educator, :researcher, :ktp, :faculty_manager, :ip_asset_manager,  # for universities
        :sponsor, # for industry
        :project_manager, :representative, # for both uni and industry
        :grantor, :investor, :adviser, :innovation_consultant, :panel_member, # external
        :participant, :guest # public

  roles_attribute :roles_mask

在我的ability.rb中,我试图将第一个能力定义为:

   user ||= User.new # guest user (not logged in)

      #users who are not signed in can read publicly available projects

      can :read, Project, :active => true, :closed => false,  &&  Project.sweep.disclosure.allusers: true

在我的 Projects 表中,我有一个名为 :close 的布尔属性。

我也有 Sweep 和 Disclosure 的模型。这些关联是:

Project.rb:
 has_one :sweep
  accepts_nested_attributes_for :sweep

Sweep. rb

belongs_to :project
has_one :disclosure
accepts_nested_attributes_for :disclosure

Disclosure.rb

belongs_to :sweep

我的公开表有一个名为 :allusers 的布尔属性。

如果 Projects.close 为 false 并且 project.sweep.disclosure.allusers 为 true,那么我希望允许访客阅读该项目。

当我按照上面的说明尝试时,我收到一条错误消息:

undefined method `id' for nil:NilClass

它指的是我的项目显示视图中的一行,上面写着:

<span class="editproject">    <% if current_user.id == @project.creator_id %>
          <%= link_to 'Edit Project', edit_project_path(@project) %> <% end %> </span>

在尝试定义能力之前,这并没有导致错误。此外,项目索引中返回的几个项目是不符合我在能力.rb 中指定的标准的项目(例如 Disclosure.allusers 未设置为 true)。

谁能看出我在上面定义这个能力时做错了什么?

【问题讨论】:

【参考方案1】:

错误是NoMethodError

undefined method `id' for nil:NilClass

正如错误所说,Rails 试图在 nil:NilClass 上调用 current_user,这意味着您的 id 对象为 nil。

所以,你应该让current_user

@current_user

【讨论】:

以上是关于Rails、Devise、Role Model 和 CanCanCan - 定义能力的主要内容,如果未能解决你的问题,请参考以下文章

Rails - Role_Model,删除分配给用户的角色

Rails,使用 Role Model gem 检查角色

方法“is_admin”在哪里?在我的 Rails 应用程序中定义?

Rails 和 Devise 的强大参数

Rails 4、Devise 和 Mandrill 电子邮件

使用 Rails 和 Devise 进行功能测试。在我的固定装置里放啥?