Scopes as filters in rails_admin

↘锁芯ラ 提交于 2019-12-22 04:15:11

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19544398/scopes-as-filters-in-rails-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!