答えて

22

まず、新しいスコープの機能を使用し、シリアライザコンテキストでcurrent_userへのアクセスを得るために:

model.active_model_serializer.new(model, scope: serialization_scope) 

class ApplicationController < ActionController::Base 
    ... 
    serialization_scope :current_user 
end 

スコープを渡すようにしてください、手動でシリアライザをインスタンス化する場合には

シリアライザの内部で、独自の認証擬似属性を追加するカスタムメソッドを追加し、scope(現在のユーザー)を使用してアクセス許可を決定します。

あなたはカンカンを使用している場合は、can?メソッドにアクセスするためにあなたの能力のクラスをインスタンス化することができます

attributes :can_update, :can_delete 

def can_update 
    # `scope` is current_user 
    Ability.new(scope).can?(:update, object) 
end 

def can_delete 
    Ability.new(scope).can?(:delete, object) 
end 
+0

私は理解していません - あなたはすぐにあなた自身の質問に答えましたか? –

+2

はい、私はしました - [この記事](http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/)を参照してください。私はこの知識を保存したかったのですが、私のブログに投稿するのはそれほど簡単ではないことがわかったので、Q&Aスタイルで投稿しました。 –

+1

@JoLiss "super.merge"スタイルの代わりに、 'attributes:can_update、:can_delete'と言って、シリアライザのメソッドとしてcan_updateとcan_deleteを定義することができます。いずれにしてもうまくいく。 – tee

2

serialization_scopeにしたいので、私は単に能力を渡します。

class ApplicationController < ActionController::Base 
... 
serialization_scope :current_ability 

def current_ability 
    @current_ability ||= Ability.new(current_user) 
end 

end 


class CommentSerializer < ActiveModel::Serializer 
    attributes :id, :content, :created_at, :can_update 

    def can_update 
    scope.can?(:update, object) 
    end 

end 

私の能力は実際には2つの変数(上記の例ではない)に基づいているため、私は他にはできません。
current_userにアクセスする必要がある場合は、単にインスタンス変数を「能力」に設定することができます。

関連する問題