ajax-datatables-rails
ajax-datatables-rails copied to clipboard
Can't Search Columns from Custom Join
Hi there,
Currently, due to the way the current application stacks are structured, I need to do a custom join in my data fetch query but I find that when I do this I cannot get search to work at all. The generated file says the following:
# Declare strings in this format: ModelName.column_name
# or in aliased_join_table.column_name format
I have my custom join aliased but when I use the alias it returns:
NameError (wrong constant name c)
The following is my data tables class:
class MyUsersDatatable < AjaxDatatablesRails::ActiveRecord
def view_columns
# Declare strings in this format: ModelName.column_name
# or in aliased_join_table.column_name format
@view_columns ||= {
first_name: { source: "c.first_name", cond: :like },
last_name: { source: "c.last_name", cond: :like },
username: { source: "MyUser.username", cond: :like },
client_id: { source: "MyUser.client_id", cond: :eq }
}
end
def data
records.map do |record|
{
# example:
first_name: record.first_name,
last_name: record.last_name,
username: record.username,
# last_visit: record.last_visit,
client_id: record.client_id,
# actions: ,
DT_RowId: record.client_id
}
end
end
def get_raw_records
MyUser
.joins("LEFT JOIN #{ENV['OTHER_APP_DATABASE']}.clients c ON my_users.client_id = c.id")
.select("my_users.username", "c.first_name", "c.last_name", "my_users.client_id")
.all
end
end
I can get it to at least load by removing the c from first_name and last_name in view_columns, but searching never works even with this change. Instead it just returns:
NameError (wrong constant name first_name)
Any help in figuring out what I'm doing wrong would be greatly appreciated.
I managed to find a solution that included me creating a custom search lambda, though I'm curious if that is the best way to handle this going forward? I don't see us having to do this much, if at all, ever again, but I'd like to know just in case.
NameError (wrong constant name c)
From your code here it should be Client.first_name and Client.last_name (for the record.client_id relation)
The source key represents the table and the column implied in the relation in order to build a SQL query.
Maybe it's clearer like that :)