10

active_model_serializersを使用して権限をシリアル化するにはどうすればよいですか?current_userモデルやシリアライザーのcan?メソッドにアクセスできません。

4

3 に答える 3

23

current_userまず、シリアライザー コンテキストで にアクセスするには、新しいスコープ機能を使用します。

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

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

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

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

CanCan を使用している場合は、Ability クラスをインスタンス化して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
于 2012-07-25T23:29:17.197 に答える
3

この機能を提供するgemを作成しました:https ://github.com/GroupTalent/active_model_serializers-cancan

于 2013-03-20T23:14:41.303 に答える
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 へのアクセスが必要な場合は、Ability にインスタンス変数を設定するだけです。

于 2014-05-23T14:58:05.550 に答える