【问题标题】:In Rails, using Cancancan/Will_Paginate how can I only show navigation links that user's can read?在 Rails 中,使用 Cancancan/Will_Paginate 如何只显示用户可以阅读的导航链接?
【发布时间】:2016-03-18 22:25:53
【问题描述】:

我同时使用cancancanwill_paginate。某些用户可以阅读以下块定义的某些报告。

能力.rb

can :read, Report do |report|
  if report.is_pro?
    if (8..12).include? Time.now.month
      (report.created_at.year != Time.now.year) || (report.author_id == user.id)
    elsif (1..4).include? Time.now.month
      (report.created_at.year < Time.now.year-1) || (report.author_id == user.id)
    else
      true
    end
  end
end

但是,当在给定页面上使用如下所示的分页链接时,限制有效,用户只能看到能够看到的报告,但是 will_paginate 链接显示为好像所有报告都是可见的。

users_controller.html.erb

@reports = Report.all.paginate(page: params[:page], per_page: 15)

report_activity.html.erb

<% @reports.each do |report| %>
  <% if can? :read, report %>
    <% render 'user_report', report: report %>
  <% end %>
<% end %>
<%= will_paginate @reports %>

我确实在我的 ActiveQuery 中找到了提到使用方法 accessible_by(current_ability) 的链接。但这意味着我需要将上面显示的Cancancan 能力块重写为哈希。我不确定如何将我当前的逻辑作为哈希来处理。

【问题讨论】:

    标签: ruby-on-rails will-paginate cancancan


    【解决方案1】:

    所以我最终做了以下事情。希望这对其他人有所帮助,但基本上它只是重新思考应该如何设置我相信......

    if (8..12).include?(Time.now.month) # Is the current month in Aug thru Dec?
      # Allowed to read reports that are before August of the current year
      can :read, Report, "((year(created_at) <> #{Time.now.year}) AND (month(created_at) >= 8)) OR reports.author_id = #{user.id}"
    
    elsif (1..4).include?(Time.now.month) # Is the current month in Jan thru April?
      # Allowed to read reports that are before August of the previous year
      can :read, Report, "(year(created_at) < #{Time.now.year-1}) AND (month(created_at) <= 7) OR reports.author_id = #{user.id}"
    
    else # or is it in May to July... wdgaf!
      can :read, Report, :all
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多