Last active
June 9, 2023 17:55
-
-
Save cdsandoval/28fc2bc8a89fa3ce68224b2b0c344416 to your computer and use it in GitHub Desktop.
Refactor ransack fiilter with search term
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function buildSearchGroups(term, searchFields) { | |
const searchGroups = []; | |
if (term) { | |
const searchTermList = term.trim().split(' '); | |
searchTermList.forEach(searchTerm => { | |
const searchGroup = { m: 'or' }; | |
searchFields.forEach(field => { | |
searchGroup[field] = searchTerm; | |
}); | |
searchGroups.push(searchGroup); | |
}); | |
} | |
return searchGroups; | |
} | |
function buildFiltersWithSearchGroups(q, searchGroups, usersFilter) { | |
if (searchGroups.length === 0) return q; | |
const modifiedQ = { ...q }; | |
const hasUsersFilter = usersFilter && Object.keys(usersFilter).length | |
const [gFirstValue] = modifiedQ.g; | |
if (hasUsersFilter) { | |
const isSimpleFilterType = usersFilter.filterType === 'simple'; | |
modifiedQ.g[0].g = isSimpleFilterType | |
? [gFirstValue, ...searchGroups] | |
: [...modifiedQ.g[0].g, ...searchGroups]; | |
} else { | |
modifiedQ.g = [{ m: 'or', g: [gFirstValue, ...searchGroups] }]; | |
modifiedQ.m = 'and'; | |
} | |
return modifiedQ; | |
} | |
const searchFields = [ | |
'selected_contract_id_eq', | |
'person_name_i_cont', | |
'person_lastname_i_cont', | |
'person_middle_name_i_cont', | |
'person_mothers_name_i_cont', | |
]; | |
const searchGroups = buildSearchGroups(term, searchFields); | |
const ransackFilters = buildFiltersWithSearchGroups(q, searchGroups, filters); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment