I'd like to create an activeadmin filter on a page for a model that has an association with the User model. I'd like to use the custom scope matches_name
, which combines the first_name
and last_name
fields. I've added that scope to the model's ransackable_scopes
method, and I am able to query it in the rails console.
I've specified the filter like so:
filter :user_matches_name, as: :string, label: "User"
However, when I load the page, it errors out with this message:
undefined method `user_matches_name_contains' for Ransack::Search<class: MyModel, base: Grouping <combinator: and>>:Ransack::Search
I've been able to create a filter on the user activeadmin page without a similar error:
filter :matches_name, as: :string, label: "User"
Is there a way to prevent either ransack or activeadmin from appending the extra _contains
on the end of the filter?
You can use ransacker to combine first_name and last_name (full_name for example) for the User class and then from ActiveAdmin resource file that has an association with the User model use this filter:
filter :user_full_name, as: :string, label: 'User'
registration of my model resource
ActiveAdmin.register MyModel do
actions :index
filter :user_full_name, as: :string, label: 'User'
end
registration of User resource
ActiveAdmin.register User do
actions :index
end
User and MyModel models
class MyModel < ApplicationRecord
belongs_to :user
def self.ransackable_associations(auth_object = nil)
%w[user]
end
def self.ransackable_attributes(auth_object = nil)
%w[created_at id id_value updated_at user_id]
end
end
class User < ApplicationRecord
ransacker :full_name do |parent|
Arel::Nodes::InfixOperation.new('||', parent.table[:first_name], parent.table[:last_name])
end
def self.ransackable_attributes(auth_object = nil)
%w[created_at first_name full_name id id_value last_name updated_at]
end
end
this code should work properly with both 3.x.x and 2.x.x versions of ActiveAdmin gem