簡體   English   中英

具有has_and_belongs_to_many的cancancan能力

[英]cancancan Abilities with has_and_belongs_to_many

我的班級用戶和頁面之間具有以下關系。

class User < ApplicationRecord
  has_and_belongs_to_many :pages
end

class Page < ApplicationRecord
  has_and_belongs_to_many :users
end

我該如何在Ability文件中讓用戶僅編輯屬於他的頁面?

class Ability
  include CanCan::Ability
  def initialize(user)
      if user.is? :page_administrator
        can :manage, Page
      end
  end
end

我嘗試以下方法,但仍然不能。

  can :manage, Page, users: { user_id: user.id }

has_and_belongs_to_many最大的has_and_belongs_to_many是無法將數據附加到has_and_belongs_to_many表。 而是使用聯接模型:

class User < ApplicationRecord
  has_many :user_pages
  has_many :pages, through: :user_pages
end

class Page < ApplicationRecord
  has_many :user_pages
  has_many :users, through: :user_pages
end

class UserPage < ApplicationRecord
  belongs_to :user
  belongs_to :page
end

類似於has_and_belongs_to_many除了它不是無頭的-您可以直接查詢UserPage 您除了需要創建UserPage模型做的唯一的事情是由重命名表users_pagesuser_pages (或pages_userspage_users )。

class RenameUsersPages < ActiveRecord::Migration[5.0]
  def change
    rename_table('users_pages', 'user_pages')
  end
end

這是必需的,因為rails會將表鏈接到常量Users::Page

現在,您可以輕松地在UserPage表上附加一個admin標志。

class AddPageAdministratorToUserPages < ActiveRecord::Migration[5.0]
  change_table :users do |t|
    t.boolean :admin, default: false
   end
end

現在,我們可以通過檢查user_pages是否存在記錄來檢查用戶是否為管理員:

class Ability
  include CanCan::Ability
  def initialize(user)
      can :manage, Page do |p|
        p.user_pages.exists?(admin: true, user: user)
      end
  end
end

暫無
暫無

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

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