簡體   English   中英

Rails cancancan獲取特定用戶的記錄

[英]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::RecordNotFoundraise 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.

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