I would like to use ActiveModelSerializers on the result of a rawSQL query in Rails. Can't find a way to do it.
sql = "SELECT * FROM table"
results = ActiveRecord::Base.connection.exec_query(sql)
options = { each_serializer: MySerializer }
output = ActiveModelSerializers::SerializableResource.new(results, options).as_json
I've tried several options:
ActiveRecord::Base.connection.execute(sql)
give a PG::Result
ActiveRecord::Base.connection.exec_query(sql)
give a ActiveRecords::Result
But none of that can be serialized.
active_model_serializers doesn't seem to be supported so consider choosing another library.
Hashes can't be serialized with your custom serializer, because they don't have
read_attribute_for_serialization. So we can wrap hashes ofresultswith such a class:After that they can be serialized: