I’m trying to use DB::Serializable
to deserialize rows from a Postgres DB into Crystal objects. It works great when a row maps to a single object, but I can’t seem to get it to map to multiple objects:
db.query_all <<-SQL, app_id, as: {App, User}
SELECT apps.*, users.* -- I specify the columns explicitly but it would just be noise here
FROM apps
JOIN app_access ON app_access.app_id = apps.id
JOIN users ON app_access.user_id = users.id
WHERE apps.id = $1
SQL
Is there a way to get crystal-db
to chop up a result row into two or more different objects?
I do this with neo4j
like this:
txn.exec_cast <<-CYPHER, {app_id: app_id}, {App, User}
MATCH (user:User)-[:GRANTED_ACCESS_TO]->(app:App)
WHERE app.id = $app_id
RETURN app, user
CYPHER
But with SQL, an ORM has to chop up the row into whole objects. It seems DB::Serializable
has enough information to do this, I just don’t know how to invoke that.
Db Serializable is very basic: just fetch from a single table. No joins, no nothing. I recommend you use a proper ORM. Maybe we should deprecate and remove serializable because it’s a bit useless.
1 Like
You might use include JSON::Serializable
, <class>.to_json
and <class>.from_json
; and then try saving your deserialize objects.