This is an example of my sql sorting problem for the Stack Overflow question.
the data can be found in the following file:
https://github.com/bigos/rails-sorting/blob/master/db/development.sqlite3
SELECT products.*, case when
(select custom_fields.value_string
from custom_fields
where custom_fields.custom_field_definition_id = 2
and custom_fields.table_record_id = products.id and custom_fields.belongs_to_table = 'product') is null
then 'default value'
when
(select custom_fields.value_string
from custom_fields
where custom_fields.custom_field_definition_id = 2
and custom_fields.table_record_id = products.id and custom_fields.belongs_to_table = 'product') is not null
then (select custom_fields.value_string from custom_fields where custom_fields.custom_field_definition_id = 2
and custom_fields.table_record_id = products.id and custom_fields.belongs_to_table = 'product')
end as sorted
from products
order by sorted;
2|onions|veg|2015-12-24 18:11:54.977313|2015-12-24 18:11:54.977313|default value
3|carrots|veg|2015-12-24 18:12:12.589968|2015-12-24 18:12:12.589968|default value
4|cola|drink|2015-12-24 18:12:28.080403|2015-12-24 18:12:28.080403|default value
1|orange|fruit|2015-12-24 18:11:44.610050|2015-12-24 18:11:44.610050|fruits of the world
How do I properly sort products by associated custom fields using default values where necessary? Can it be translated to Arel?