[英]Rails cancancan fetching records for specific user
我只需要使用CanCanCan在特定條件下從數據庫中獲取特定記錄。 這是我的數據模型。
class User < ApplicationRecord
has_many :regions_users
end
class RegionsUser < ApplicationRecord
belongs_to :region
end
class Region < ApplicationRecord
has_many :regions_users
has_many :sites
end
class Site < ApplicationRecord
belongs_to :region
has_many :offers
end
class Offer < ApplicationRecord
belongs_to :site
end
例如,將一個用戶分配給兩個區域,這意味着該用戶user.regions_users
返回兩個RegionsUser [RegionsUser1,RegionsUser2]的數組。 RegionsUser1屬於Region A,RegionsUser2屬於Region B,因此,如果我以用戶身份登錄,則我是可以監視屬於那些區域的數據的區域用戶。 現在,我需要顯示屬於那些區域(區域A和區域B)的商品。 這意味着,用戶無法訪問屬於區域A和區域B以外的區域的商品,因此訪問/offers/3
應該會出現Access Denied
錯誤。
我可以從RegionsUser中拉出區域:
region_ids = user.regions_users.pluck(:regions_id)
然后提供:
Offer.joins(:site).where(sites: { region_id: region_ids })
can :update, Project, ["priority < ?", 3] do |project|
project.priority < 3
end
但我想不出任何解決方案。 我將不勝感激。
UPDATE
這種方法可以解決,但不是顯示“訪問被拒絕”頁面,而是引發“ 404頁面未找到”錯誤。
offers_controller.rb
def offer
@offer ||= Offer.accessible_by(current_ability).find(params[:id])
end
ability.rb
if user.region_user?
region_ids = user.regions_users.pluck(:region_id)
can :read, Offer, site: { region_id: region_ids }
end
更新2
我可以捕獲ActiveRecord::RecordNotFound
並raise CanCanCan::AccessDenied
但這是一種解決方法。 我希望CanCanCan可以處理授權部分。 我可以在控制器中拉出記錄並引發期望,但這與CanCanCan無關,對嗎?
我認為您在控制器中需要load_and_authorize_resource
。 我認為這不會提高
除非您這樣做,否則請raise CanCan::AccessDenied.new("Not authorized!", :read, Article)
。 accessible_by(currrent_ability)
只是將結果集的范圍限定為您的能力文件中定義的結果集
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.