Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scopes as filters in rails_admin

I am using rails_admin in my app. I have some scopes on my models, following is an example:

class User < ActiveRecord::Base

  scope :unconfirmed, where('confirmed_at IS NULL')

end

Is it possible in rails_admin to get access to those scope as a filter? Like you can in active admin. Like adding a button somewhere on in the users section.

Thanks

like image 369
Arthur Avatar asked Oct 23 '13 14:10

Arthur


2 Answers

I know it is a very old issue but someone redirected me to this thread. You can achieve this easily by configuring the rails_admin as follows

# /config/initializers/rails_admin.rb
config.model User do
    list do
        scopes [nil, :unconfirmed]
    end
end

This will insert two tabs on top of the list labelled All and Unconfirmed with the records filtered in respective tabs. Clicking those tabs will fire a query applying your custom scope

Hope it helps.

like image 173
Aayush Avatar answered Oct 21 '22 09:10

Aayush


I've managed to do this successfully by adding a custom rails_admin action.

More details: https://github.com/sferik/rails_admin/wiki/Custom-action

For example:

# in lib/rails_admin/unconfirmed.rb

require 'rails_admin/config/actions'
require 'rails_admin/config/actions/base'

module RailsAdminUnconfirmed
end

module RailsAdmin
  module Config
    module Actions

      class Unconfirmed < RailsAdmin::Config::Actions::Base
        RailsAdmin::Config::Actions.register(self)

        register_instance_option :controller do
          Proc.new do
            @objects = User.unconfirmed
            render "index"
          end
        end

        register_instance_option :collection do
          true
        end
      end
    end
  end
end

The key is that it's a 'collection' action. Then you add it to the rails_admin setup:

# in config/initializers/rails_admin.rb
# require File.join(Rails.root, "lib", "rails_admin", "unconfirmed")

RailsAdmin.config do |config|
  config.actions do
    # root actions
    dashboard
    # collection actions
    index
    unconfirmed do
      only 'User'
    end
  end
  # snip!
end

This new action will appear at the index level of the User model.

like image 2
Chris O'Sullivan Avatar answered Oct 21 '22 08:10

Chris O'Sullivan