在我的應用程序中,我有權限表,它存儲了用戶可以執行的所有邏輯。 隨着權威,我想允許用戶創建新的運動,如果權限表允許。用戶可以訪問廣告活動,並創建新的,如果權限表包含以下信息:Rails 5:用戶通過權限表創建記錄的權限與權威人士
- permitable_type:Sysmodule //另一個表,我存儲在系統部分信息,在廣告活動是
- permitable_id之一:2 //意味着廣告活動從Sysmodule
- 級別:3 //意味着用戶可以在廣告活動部編輯的東西
到目前爲止,我不斷收到錯誤「Pundit :: NotDefinedError」,無法找到無政策政策/ application_policy.rb是標準的,沒有變化。 顯然我做錯了。我如何正確執行此授權?非常感謝您的幫助!我在Rails 5 + Pundit上。
型號/ permission.rb
class Permission < ApplicationRecord
belongs_to :permitable, polymorphic: true
belongs_to :user
enum level: {owner: 1, view: 2, edit: 3}
end
型號/ user.rb
has_many :permissions
has_many :campaigns, through: :permissions, source: :permitable, source_type: 'Campaign' do
def owner_of
where('`permissions`.`level` & ? > 0', Permission::owner)
end
end
has_many :sysmodules, through: :permissions, source: :permitable, source_type: 'Sysmodule' do
def can_access
where('`permissions`.`level` & ? > 1', Permission::can_access)
end
end
控制器/ campaigns_controller.rb
def new
@campaign = Campaign.new
authorize @campaign
end
政策/ campaign_policy.rb
class CampaignPolicy < ApplicationPolicy
attr_reader :user, :campaign, :permission
@user = user
@permission = permission
end
def new?
user.permission? ({level: 3, permitable_type: "Sysmodule", permitable_id: 2})
end
組
的意見/運動/ index.html.erb
<% if policy(@campaign).new? %>
</li>
<li><%= link_to "New campaign", new_campaign_path(@campaign) %></li>
</li>
<% end %>
加盟的一切,雖然在'permissions'表中的多態性關係將是一個巨大的性能問題。通過'::'('Permission :: owner')調用類方法在Ruby中不是很好的樣式,因爲它看起來像訪問模塊常量。 – max
我認爲你要做的是'Permission.levels [:owner]'。 'Permission :: owner'實際上等於'Permission.where(level :::owner)' – max
@max對於任何對象(例如Campaign),您可以爲任何對象設置權限(查看/編輯/刪除)用戶?我們假設,從數據庫中的10個廣告系列中,用戶可以查看兩個,編輯兩個,是兩個的所有者,但不能訪問四個。 – matiss