hi-nakamura
8/18/2014 - 9:05 AM

Using pundit

Using pundit

class SampleController < ApplicationController
  before_action :check_authority_to_show, only: [:show]
  
  def list(criteria, page)
    models = policy_scope(ModelName.all)
    ...
  end
  
  def show(id)
    ...
  end
...
class ModelNamePolicy < ApplicationPolicy
  class Scope < Struct.new(:user, :scope)
    def resolve
      if user.admin?
        scope
      else
        scope.where(xxx: xxx)
      end
    end
  end

  def show?
    if user.admin?
      return true
    else
      return true if record.xxx == xxx
    end
    false
  end
end
class ApplicationController < ActionController::Base
  include Pundit

  def check_authority_to_show
    model = ModelName.find_by(id: params[:id])
    return if model.nil?
    unless Pundit.policy(current_user, model).show?
      redirect_to :user_root, flash: { error: Settings.no_authority }
    end
  end
...
# Gemfile
bundle install 'pundit'

# generate policies -> app/policies/application_policy.rb
rails g pundit:policy post