ruby-on-rails – CanCan和数据集
发布时间:2020-12-17 02:27:58 所属栏目:百科 来源:网络整理
导读:我已经在这方面苦苦挣扎了一段时间,我终于到了CanCan似乎不允许你授权收集记录的地步.例如: ads_controller.rb def index @ads = Ad.where("ads.published_at = ?",30.days.ago).order("ads.published_at DESC") authorize! :read,@adsend ability.rb def i
我已经在这方面苦苦挣扎了一段时间,我终于到了CanCan似乎不允许你授权收集记录的地步.例如:
ads_controller.rb def index @ads = Ad.where("ads.published_at >= ?",30.days.ago).order("ads.published_at DESC") authorize! :read,@ads end ability.rb def initialize(user) user ||= User.new # Guest user if user if user.role? :admin # Logged in as admin can :manage,:all else # Logged in as general user can :read,Ad can :read_own,Ad,:user_id => user.id can :create,Ad end else # Not logged in (Guest) can :read,Ad end end 这会在尝试访问索引操作时导致未经授权的访问消息. You are not authorized to access this page. 但是,如果您在索引操作中更改授权调用以检查Ad类而不是像这样的集合 def index @ads = Ad.where("ads.published_at >= ?",30.days.ago) authorize! :read,Ad end ……工作正常 任何帮助解释这一点将不胜感激. 提前致谢. PS.在尝试解决这个问题时,我最初获得了重定向循环.事实证明,你在应用程序控制器中提供了一个推荐的rescue_from,它给你提供了很好的错误信息.如果您的root_path设置为您授权的同一个地方!如果调用不正确(或失败),您将获得重定向循环.评论出来救援从这一方面学到了很多. 解决方法
CanCan不是设计用于那样的.您可以检查用户是否具有模型类(例如Ad)或单个实例(例如@ad)的权限.
我建议你只使用accessible_by来过滤你的收藏: @ads = Ad.where("ads.published_at >= ?",30.days.ago).accessible_by(current_ability) # @ads will be empty if none are accessible by current user raise CanCan::AccessDenied if @ads.empty? # handle however you like 另一种方法是根据用于检索集合的条件定义自定义权限: # ability.rb can :read_ads_from_past_month,["ads.published_at >= ?",30.days.ago] # in your controller def index authorize! :read_ads_from_past_month,Ad @ads = Ad.where("ads.published_at >= ?",30.days.ago) end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |