Custom search for belongs_to

Author: SegFaultAXCreated Dec 28, 2011Updated Feb 19, 2025
Labelsenhancement

Suppose I have the following models:

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, :through => :friendships
end

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User"
end

The user_id and friend_id fields in the #create and #update actions of the admin panel use a searchable drop down. I'd like to customize the search function to, for example, only use User.where(:username => query) or User.where(:email => query). The default seems to search every column on the table and is very time consuming for tables with tens-of-thousands of rows. The documentation on scoping the association and configuring the model in the initializer is unclear to me.

Source: railsadminteam/rails_admin