是否可以在模型中使用cancan? [英] Is it possible to use cancan in a model?

查看:99
本文介绍了是否可以在模型中使用cancan?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有状态机的模型,我想将不同的状态/事件/转换限制给不同的用户.

I have a model with a statemachine and i want to limit different states/events/transitions to different users.

如何使用此模型访问当前用户和功能?

How can i access current user and ability in this model?

推荐答案

您可以针对模型提供的任何方法在cancan中定义能力.状态机转换本身就是模型提供的方法,因此只需像设置其他任何方法一样设置您的能力即可.

You can define abilities in cancan against any methods provided by the model. State machine transitions are themselves methods provided by the model, so just set up your abilities as you would for any other methods.

例如,给定一个简单的模型:

For example, given a simple model:

class Order < ActiveRecord::Base

  state_machine :initial => :new do

    event :start_processing do
      transition :new => :processing
    end

    event :complete_order do
      transition :processing => :complete
    end

    event :escalate_order do
      transition :processing => :escalated
    end

    event :complete_escalated_order
      transition :escalated => :complete
    end

    state :new
    state :processing
    state :escalated
    state :complete
  end

end

您可以这样定义能力:

class Ability

  if user.role? :orderer
    can [:start_processing, :escalate_order, :complete_order], :orders
  end
  if user.role? :manager
    can :complete_escalated_order, :orders
  end

end

编辑-我应该添加,然后您将在处理用户请求的控制器中使用以下功能:

EDIT - I should have added, that you would then use these abilities in your controllers handling the user requests:

class OrdersController < ApplicationController

  def complete
    @order = Order.find_by_ref(params[:id])

    if @order.can_complete_order?
      authorize! :complete_order, @order
      @order.complete_order
    elsif @order.can_complete_escalated_order?
      authorize! :complete_escalated_order, @order
      @order.complete_escalated_order
    else
      redirect_to root_url, :notice => "Order cannot be completed"
    end

    redirect_to my_queue_path, :notice => "Order #{@order.ref} has been marked as complete."

结束

这篇关于是否可以在模型中使用cancan?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆