2012-03-08 22 views
1

私はステートマシンのモデルを持っています。さまざまな状態/イベント/遷移を別のユーザーに制限したいのです。モデルでcancanを使用することはできますか?

このモデルで現在のユーザーと能力にアクセスするにはどうすればよいですか?

+0

私は赤を持っています。http://stackoverflow.com/questions/3293400/access-cancans-can-method-from-a-modelでも、howtoを取得するユーザーが理解できません(user.can?(:update、@ article ))をモデル – tonymarschall

+1

に入れるhttp://stackoverflow.com/questions/1568218/access-to-current-user-from-within-a-model-in-ruby-on-railsを参照してください。ユーザーをモデルに渡すことは合理的です。具体的には、現在のパターンにアクセスすることは、おそらくアンチパターンです。 – Jonah

答えて

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 

EDIT - 私はあなたが、あなたのコントローラ内でこれらの能力を使用することを、追加している必要がありますユーザーの要求を処理:

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." 

エンド

+0

素晴らしい!今日の午後はテストをします。ユーザーが選択できる選択肢のハウツー制限イベントに関するヒントを教えてください。現在、私は可能なすべてのイベントを取得するために@ item.state_transitionsを使用しています。 – tonymarschall

+0

私はおそらく、役割が可能な遷移を定義し、ユーザーの割り当てられた役割を通してそれらを見つけるでしょう。 – Jon

関連する問題