簡體   English   中英

Rails,Devise,角色模型和CanCanCan-定義功能

[英]Rails, Devise, Role Model and CanCanCan - defining abilities

我正在使用Rails 4制作一個Web應用程序。

我正在嘗試使用CanCanCan定義各種角色的能力。

我有一個用戶模型和一個個人檔案模型。 每個用戶可以有許多個人資料。 每個配置文件可以具有不同的角色。

在我的Profile.rb中,我的角色(使用Role Model 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

在我的bility.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表中,我有一個名為:closed的布爾屬性。

我也有“掃除和披露”模型。 關聯是:

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.closed為false並且project.sweep.disclosure.allusers為true,那么我想允許訪客閱讀Project。

當我如上所述嘗試時,出現錯誤消息:

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>

在嘗試定義能力之前,這不會引起錯誤。 另外,在項目索引中返回的幾個項目是不符合我在ability.rb中指定的條件的項目(例如Disclosure.allusers未設置為true)。

有人能看到我在定義上述功能時做錯了什么嗎?

錯誤是NoMethodError

undefined method `id' for nil:NilClass

如錯誤所述,Rails嘗試在nil:NilClass上調用current_user,這意味着您的id對象為nil。

所以,你應該讓current_user

@current_user

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM