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?
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
Try this:
ActiveAdmin.register Call do
filter :user_name
end
Since ActiveAdmin uses meta_search
for filters their doc is very helpful: https://github.com/ernie/meta_search
You can use nested resources from InheritedResource which is used by ActiveAdmin, so your list is automatically filtered by the parent.
ActiveAdmin.register User do
# this is the parent resource
end
ActiveAdmin.register Call do
belongs_to :user # nested below resource user
end
You can then use rake routes to see the new nested routes, generated by ActiveAdmin :) Hope it helps
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.
I'd say it hugely depends on the types of associations you have between your models - it took me hours to figure this out.
Example
class User < ActiveRecord::Base
belongs_to :user
end
class Email < ActiveRecord::Base
has_one :email
end
To filter users based on their emails, you do this (don't forget the as: :string
part as it gives you access to Ransack search methods such as contains and the likes)
ActiveAdmin.register User do
filter :user_email, :as => :string
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.