ruby-on-railssearchrubygemsadministrate

Search by id in Administrate Gem in Rails


By default Administrate Gem gives us a feature where we can search record by name. But now I am trying to search record by ID in search bar of admin Dashboard, like this

ATTRIBUTE_TYPES = {
  id: Field::Number,
  name: Field::String,
}.freeze

But I am not able to search records by its ID, I try this but didn't work

ATTRIBUTE_TYPES = {
  id: Field::Number.with_options(searchable: true),
  name: Field::String,
}.freeze

I am expecting to serach records by two things, like ID and Name also


Solution

  • In administrate gem give by default with_options(searchable :true or false) it is only for associated things for example(have a two models with name of user and employee with has_one association to search the employee thing in user page with_options(searchable: true) will work) you have search by id in admin dashboard use this code in your admin controller

    def index
      authorize_resource(resource_class)
      search_term = params[:search].to_s.strip
      resources = filter_resources(scoped_resource, search_term: search_term)
      resources = apply_collection_includes(resources)
      resources = order.apply(resources)
      resources = resources.page(params[:_page]).per(records_per_page)
      page = Administrate::Page::Collection.new(dashboard, order: order)
    
      render locals: {
        resources: resources,
        search_term: search_term,
        page: page,
        show_search_bar: show_search_bar?,
      }
    end
    
    def filter_resources(resources, search_term:)
      Administrate::Search.new(
        resources,
        dashboard,
        search_term,
      ).run
     if search_term.present?
        resources.where(id: search_term)
      else
        resources.all
      end
    end