cancanのload_and_authorize_resourceend

2322 ワード

使用
class BooksController < ApplicationController
  load_and_authorize_resourceend
end

対応
14
15
16
# File 'lib/cancan/controller_additions.rb', line 14

def load_and_authorize_resource(*args)
  cancan_resource_class.add_before_filter(self, :load_and_authorize_resource, *args)
end

これは対応です
# File 'lib/cancan/controller_resource.rb', line 24
def load_and_authorize_resource
  load_resource
  authorize_resource
end

2つのセクションに分けられます.
一、
# File 'lib/cancan/controller_resource.rb', line 29
def load_resource
  unless skip?(:load)
    if load_instance?
      self.resource_instance ||= load_resource_instance
    elsif load_collection?
      self.collection_instance ||= load_collection
    end
  end
end

これはまた2つの部分に分かれています.
# File 'lib/cancan/inherited_resource.rb', line 4

def load_resource_instance
  if parent?
    @controller.send :association_chain
    @controller.instance_variable_get("@#{instance_name}")
  elsif new_actions.include? @params[:action].to_sym
    resource = @controller.send :build_resource
    assign_attributes(resource)
  else
    @controller.send :resource
  end
end

および
def load_collection                                                 
  resource_base.accessible_by(current_ability, authorization_action)
end        
def current_ability
  @controller.send(:current_ability)
end
def authorization_action
  parent? ? :show : @params[:action].to_sym
end
---------
  • - (Object) accessible_by(ability, action = :index)Returns a scope which fetches only the records that the passed ability can perform a given action on.
  • @articles = Article.accessible_by(current_ability)
    @articles = Article.accessible_by(current_ability, :update)

                                                             
    別のセクション:
    # File 'lib/cancan/controller_resource.rb', line 39
    
    def authorize_resource
      unless skip?(:authorize)
        @controller.authorize!(authorization_action, resource_instance || resource_class_with_parent)
      end
    end