diff --git a/app/controllers/concerns/user_defined_fields/queryable.rb b/app/controllers/concerns/user_defined_fields/queryable.rb index 1770d0b..746de43 100644 --- a/app/controllers/concerns/user_defined_fields/queryable.rb +++ b/app/controllers/concerns/user_defined_fields/queryable.rb @@ -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 @@ -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 @@ -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