Skip to content

Commit

Permalink
UDF #27 - Adding a table prefix to the user_defined_fields sort and s…
Browse files Browse the repository at this point in the history
…earch methods
  • Loading branch information
dleadbetter committed May 23, 2023
1 parent 8be734a commit 033d505
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions app/controllers/concerns/user_defined_fields/queryable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@ def apply_user_defined_sort(query)

return query if user_defined_field.nil?

table_alias = table_name(user_defined_field.table_name)

case user_defined_field.data_type
when UserDefinedField::DATA_TYPES[:date]
query.order(Arel.sql("(user_defined->>'#{sort_by}')::TIMESTAMPTZ #{sort_direction}"))
query.order(Arel.sql("(#{table_alias}.user_defined->>'#{sort_by}')::TIMESTAMPTZ #{sort_direction}"))
when UserDefinedField::DATA_TYPES[:number]
query.order(Arel.sql("(user_defined->>'#{sort_by}')::DECIMAL #{sort_direction}"))
query.order(Arel.sql("(#{table_alias}.user_defined->>'#{sort_by}')::DECIMAL #{sort_direction}"))
else
query.order(Arel.sql("user_defined->>'#{sort_by}' #{sort_direction}"))
query.order(Arel.sql("#{table_alias}.user_defined->>'#{sort_by}' #{sort_direction}"))
end
end

Expand All @@ -40,13 +42,13 @@ def search_user_defined(query)
searchable: true
})

fields = fields_query.pluck(:column_name)
fields = fields_query.pluck(:table_name, :column_name)
return query if fields.size == 0

or_query = nil

fields.each do |name|
attribute_query = item_class.where("user_defined->>'#{name}' ILIKE ?", "%#{params[:search]}%")
fields.each do |table, name|
attribute_query = item_class.where("#{table_name(table)}.user_defined->>'#{name}' ILIKE ?", "%#{params[:search]}%")

if or_query.nil?
or_query = attribute_query
Expand All @@ -57,6 +59,12 @@ def search_user_defined(query)

query.or(or_query)
end

private

def table_name(name)
name.constantize.table_name
end
end

end
Expand Down

0 comments on commit 033d505

Please sign in to comment.