Search gem. You can easily implement a search in the column of that table or related table. https://github.com/activerecord-hackery/ransack However, if you want to narrow down by complicated search conditions or conditions other than columns, you need to devise a little.
I want to search for some elements with ʻAND and the rest with ʻOR
.
The query looks like this:
SELECT DISTINCT sample_models.*
FROM sample_model
WHERE (sample_models.column_1 = '202001' AND sample_models.column_2 = 'Hokuto Matsumura')
AND ( sample_models.column_3 = 'Jesse' OR sample_models.column_4 = 'Juri Tanaka' )
ORDER BY sample_models.id ASC
group = {
"0" => {
m: "and",
column_1: "202001",
column_2: "Hokuto Matsumura"
},
"1" => {
m: "or",
column_3: "Jesse",
column_4: "Juri Tanaka"
}
}
#result
SampleModel.search(g: group).result
By devising the hash assigned to group, you can manipulate the conditions of grouping, AND, and OR as you like. Convenient! However, if you know that the readability will be reduced or if you do such irregular things, it will cost you to study, so if you know that the search conditions will be out of ransack from the beginning, do not force it to match ransack and do it yourself. I think it's better to write a query.
Recommended Posts