Activeadmin custom filter and scope for custom index records Rails 4

Mani David picture Mani David · Oct 20, 2014 · Viewed 7.7k times · Source

Active Admin provides custom filters and scopes that are displayed on the index page like so:

my admin app/admin/compensatory_off.rb code is

ActiveAdmin.register CompensatoryOff do

scope :pending, default: true
scope :approved

filter :claim_date, collection: proc { CompensatoryOff.all.map(&:claim_date) }

My Controller for index action : 

controller do
  def index
    @page_title = "Comp-Off"
    index! do |format|
       if (current_user.has_role? :HRMS_Supervisor)
           @compensatory_offs = CompensatoryOff.get_subordinate_employees_comp_offs(current_user).page(params[:page]).per(10)
         else
           @compensatory_offs = current_user.employee.compensatory_offs.order("compensatory_offs.claim_date DESC").page(params[:page]).per(10) if current_user.employee
         end

         format.html {
           render "active_admin/resource/index"
         }
       end
     end
  end
end

i used both filter and scope in the above code.

in my model i defined the scopes also ,

class CompensatoryOff < ActiveRecord::Base
  scope :pending, ->{where(status: "Pending Approval")}
  scope :approved, ->{where(status: "Approved")}

  #scope :claim_date_eq, -> (claim_date) {where(claim_date: claim_date)}
end 

but in the above code both scope and filters are not working. the index page is not resulting anything it displaying all the records.

Note : when i remove my custom index action from the controller both the scope and filters working fine.

my admin app/admin/compensatory_off.rb code is

ActiveAdmin.register CompensatoryOff do

scope :pending, default: true
scope :approved

filter :claim_date, collection: proc { CompensatoryOff.all.map(&:claim_date) }

My Controller for index action : 

controller do
end

end

How the index action resource is getting fetched by default and i want to override the index resource with my own condition.

any thing need to add with the index action,

Please any help me to achieve this, am struggling a lot to find the result.

Thanks.

Answer

Mani David picture Mani David · Oct 20, 2014

using scoped_collection its working,

controller do
    def scoped_collection
      if (current_user.has_role? :HRMS_Supervisor)
        @leave_availed_details = LeaveAvailedDetail.get_subordinate_employees_leaves(current_user).page(params[:page]).per(10)
      else
        @leave_availed_details = current_user.employee.leave_availed_details.order("leave_availed_details.status DESC").page(params[:page]).per(10) if current_user.employee
      end
    end

    # def index
    #   #@page_title = "Leave Details"
    # end
end 

for pagination use the below code.

before_filter :only => :index do
      @per_page = 10
    end