1

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?

3
  • The filters argument gives filters to append to the first ransack predicate, so that example attempts to find :user_matches_name_user_matches_name Commented Mar 20, 2024 at 20:22
  • 1
    What happens if you just change it to filter :user_name_matches, as: :string, label: "User" and add that as a ransackable_scope or better yet maybe create a custom ransacker and utilize that. Commented Mar 20, 2024 at 20:29
  • 1
    A custom ransacker gets around the problem. Thanks! Commented Mar 20, 2024 at 21:08

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.