【问题标题】:Rails 5 with CanCanCan - How to filter list for an index action带有 CanCanCan 的 Rails 5 - 如何过滤索引操作的列表
【发布时间】:2018-06-07 15:35:35
【问题描述】:

我正在制作一个用于学习目的的系统。

该系统为用户控制医院轮班。用户应该只看到他的班次。

我正在使用 CanCanCan 进行授权控制。

所以对于索引页面,我有控制器操作:

class UsersController < ApplicationController
    def index
        @users = User.all
    end
end

在 index.html.erb 中

<% @shifts.each do |shift| %>
    <% if can? :read, shift %>
      <tr>
          <td><%= shift.date %></td>
      </tr>
    <% end %>
<% end %>

在我有能力方面:

class Ability
    include CanCan::Ability

    def initialize(user)
        if user
            can :manage, Shift, user_id: user.id
        end
    end
end

如果用户没有任何班次,我想向他显示一条消息。

但是在 index html 页面中使用 can 方法,因为如果列表不为空但没有 shift 当前用户可以看到我不能直接在 @shift 中使用空方法。

是否可以在用户控制器的索引操作中过滤列表?

【问题讨论】:

    标签: ruby-on-rails ruby cancancan


    【解决方案1】:

    您在这里提出了几个不同的问题,很难单独回答,因此我将采取更广泛的方法,希望能回答我认为您遇到的一些基本问题。

    第一件事是第一:Cancancan 不做任何与查询数据库相关的事情。康康康舞由您决定。

    我没有看到@shifts 的定义位置,所以我假设它在您的ShiftsController 中——而索引操作应该显示给定用户的班次。

    给定的用户通常是 Rails 应用程序中的current_user — 这种身份验证是由诸如 Devise 之类的东西完成的。如果您的关联设置正确,您可以执行@shifts = current_user.shifts

    但是,如果您想按用户过滤班次——例如拥有 /users/:id/shifts 的 RESTful 路由——您将拥有如下所示的路由:

    resources :users do 
      member do
        get :shifts => 'users#shifts'
      end
    end
    

    这将映射到您的 UsersController 使用方法 shifts。

    在该方法中,您将拥有一个 :id 参数,其中包含您期望从显示操作中获得的值。

    @shifts = Shift.where(:user_id =&gt; params[:id])

    现在,如果您想过滤 ShiftsController#index 方法上的班次,您可以使用以下内容:

    @shifts = Shift.where(:user_id =&gt; params[:user_id])

    您的 URL 可能看起来像 /shifts?user_id=1

    现在,如果用户没有任何班次,@shifts 将返回一个空数组 — 表示没有与您的数据库查询匹配的行。因此,你可以在你的视图中做一些简单的逻辑,

    &lt;% if @shifts.empty? %&gt; No shifts. &lt;% else %&gt; ... things to list shifts &lt;% end %&gt;

    【讨论】:

    • 如果您使用load_resource 或load_and_authorize_resource,cancancan 将为您加载数据库记录。例如,如果您有一个索引操作,cancancan 会为您执行以下操作:@shifts = Shift.accessible_by(current_ability)。这是有关该功能的文档的链接:github.com/CanCanCommunity/cancancan/wiki/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多