我有一个带状态机的模型,我希望将不同的状态/事件/转换限制为不同的用户。
如何在此模型中访问当前用户和能力?
答案 0 :(得分:2)
您可以针对模型提供的任何方法在cancan中定义能力。状态机转换本身就是模型提供的方法,所以只需像设置其他方法一样设置你的能力。
例如,给出一个简单的模型:
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
编辑 - 我应该补充一点,然后您将在控制器中使用这些功能来处理用户请求:
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."
端