簡體   English   中英

在Rails中,使用Cancancan / Will_Paginate如何只顯示用戶可以閱讀的導航鏈接?

[英]In Rails, using Cancancan/Will_Paginate how can I only show navigation links that user's can read?

我正在使用cancancanwill_paginate 某些用戶具有閱讀以下功能塊定義的某些報告的能力。

能力

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 Ability塊重寫為哈希。 我不確定如何將當前邏輯作為哈希值執行。

因此,我最終要做的是以下內容。 希望這可以對其他人有所幫助,但是我基本上只是在重新考慮應該如何設置它...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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