Dear forum seniors,
As a newbier with Rails development, I’ve recently encountered a perplexing issue and would appreciate the help of experienced members to resolve it. I hope to achieve a fuzzy search on various fields of a model through the following function. However, I encounter an error when it involves fields with the inet
property. I’ve been struggling to find a good solution and would appreciate it if you could take a look. Thank you!
STRING_COLUMN_TYPES = %i[text string citext].freeze
INET_COLUMN_TYPES = %i[inet].freeze
NUMBER_COLUMN_TYPES = %i[integer float].freeze
def build_arel_filters(model, column_names, keyword)
arel_table = model.arel_table
column_names.map do |name|
column_type = model.columns_hash[name]&.type
next unless column_type
case column_type
when *STRING_COLUMN_TYPES
arel_table[name].matches("%#{keyword}%")
when *INET_COLUMN_TYPES
nil
when *NUMBER_COLUMN_TYPES
arel_table[name].eq(keyword.to_f) if keyword.match?(/\A\d/)
else
arel_table[name].eq(keyword)
end
end.compact
end
def build_arel_or_query(filter_array)
filter_array.reduce(nil) do |acc, filter|
next acc = filter unless acc
acc.or(filter)
end
end