Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter on parent object attribute in ActiveAdmin

I'd like to be able to filter an object based on an attribute of it's parent:

class Call < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :calls
end

I'd like to be able to do this:

ActiveAdmin.register Call do
  filter :user
end

and have it filter on user.name, rather than present a select of all users. Can this be done?

like image 437
David Moulton Avatar asked Oct 26 '11 22:10

David Moulton


2 Answers

Denis's solution almost worked for me. I just needed to add the filter type. For example:

ActiveAdmin.register Call do
  filter :user_name, :as => :string
end
like image 195
Justin Thiele Avatar answered Oct 02 '22 10:10

Justin Thiele


In the next release of ActiveAdmin (I work with 1.0.0.pre) you can use Ransack methods. So, let say you have an Article, which belongs_to User.

You will have the following admin/article.rb file

ActiveAdmin.register Article do

  controller do
    def scoped_collection
      Article.includes(:user)
    end
  end  

  index do      
   column :id
   column :created_at
   column :title
   column("Author", sortable: 'users.first_name') { |item| link_to item.user.full_name, user_path(item.user) }
   actions
  end

  filter :user_first_name_cont, :as => :string
  filter :user_last_name_cont, :as => :string  

end

Here, user_first_name_cont is ransack method which filters on associated user first_name and 'cont' means contains.

like image 40
hellalright Avatar answered Oct 02 '22 11:10

hellalright