繁体   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