Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save christopherstyles/1d49606c71bbd6ce0b9f to your computer and use it in GitHub Desktop.

Select an option

Save christopherstyles/1d49606c71bbd6ce0b9f to your computer and use it in GitHub Desktop.
ActiveAdmin filter, for a has_many :through association
# 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