Created
December 15, 2015 23:29
-
-
Save christopherstyles/1d49606c71bbd6ce0b9f to your computer and use it in GitHub Desktop.
ActiveAdmin filter, for a has_many :through association
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # app/models/user.rb | |
| class User < ActiveRecord::Base | |
| has_many :permissions | |
| has_many :roles, through: :permissions | |
| scope :by_role, lambda { |role_ids| | |
| joins(:permissions).where(permissions: { role_id: Array.wrap(role_ids) }) | |
| } | |
| ransacker :role, | |
| formatter: proc { |role_ids| | |
| matches = User.by_role(role_ids).map(&:id) | |
| matches.any? ? matches : nil | |
| } do |parent| | |
| parent.table[:id] | |
| end | |
| end | |
| # app/models/role.rb | |
| class Role < ActiveRecord::Base | |
| has_many :permissions | |
| has_many :users, through: :permissions | |
| validates :name, uniqueness: true | |
| end | |
| # app/models/permission.rb | |
| class Permission < ActiveRecord::Base | |
| belongs_to :role, counter_cache: :users_count | |
| belongs_to :user | |
| end | |
| # admin/user.rb | |
| ActiveAdmin.register User do | |
| filter :role_in_all, as: :select, | |
| multiple: true, | |
| collection: -> { Role.order(name: :asc).all } | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment