Be able to search through a STI Field::BelongsTo
Created by: daveharris
Hi,
I am using STI for authentication, so a base User
, sub-classes Client
, Host
and Administrator
.
One model which uses these classes is Appointment
which is defined like below:
class Appointment < ApplicationRecord
belongs_to :client
belongs_to :host
end
Therefore, I have defined my Adminstrate dashboard like so:
class AppointmentDashboard < Administrate::BaseDashboard
ATTRIBUTE_TYPES = {
id: Field::Number,
client: Field::BelongsTo
host: Field::BelongsTo
}
end
I just realised that we are missing the ability to search, which is super important. For example show all of Jim's Appointments.
Looking at at the documentation I came up with:
client: Field::BelongsTo.with_options(class_name: 'User', searchable: true, searchable_field: 'first_name')
However, this doesn't work because when creating the SQL query, it adds name of the field (client
) to searchable_field
, coming up with clients.first_name
. I need it to be users.first_name
because rails know that client
is an STI. I've attached the query it produces , but it basically boils down to
WHERE (LOWER(CAST("clients"."first_name" AS CHAR(256))) LIKE '%lily%')
I attempted to add class_name: 'User'
to with_options
but that doesn't seem to have any effect.
I saw that there is a gem https://github.com/fishpercolator/administrate-field-type but that is for adding the type
attribute to the parent, I need it the other way around.
And I doing something wrong?
Thanks for you help. Loving Administrate - provided me so many quick wins Dave