How to concatenate strings on related column like STRING_AGG with sort?
I have a simple has_many relation with parts:
And each part has a simple text field and a part number:
I'd like to concatenate all text fields, sorted by part number, similar to how one would do it with STRING_AGG in postgres, preferably in a calculation.
I was hoping a simple string_join would do it:
But alas that doesn't work:
Any ideas?
10 Replies
Looking at the error message, have you tried
or whatever seperator you want
Yeah sorry, that gives me the same error message
ah, I think you need an aggregate
Maybe I'm supposed to use aggregates instead. The documentation has some elusive reference to a "StringAgg" here: https://hexdocs.pm/ash/dsl-ash-resource.html#aggregates-custom
There's a hint in AshPostgres too but that doesn't help me very much: https://hexdocs.pm/ash_postgres/AshPostgres.CustomAggregate.html
Yes! Thank you!
And now I also need to keep it sorted.
I've tried to add sort under the has_many relationship:
That sorts fine when I fetch the parent record and related fields, but it doesn't seem to have any effect on the calculation
My mistake! Sorting in the relation does work, I just messed up my tests 🙂
As an aside, you can accomplish the same with an inline postgres fragment like so:
Although using
string_join
is a lot nicerit looks like you should be able to pass a sort to the aggregate
you should be able to pass the options you see for aggregates in the dsl to inline aggregates using the keyword list syntax
allthough you could argue that we should honor the sort of the relationship. would you mind opening an issue on github for that please

Yeah sorry, it does work I just messed up my tests
Everything works great now 🙂
Although I'm not able to find the documentation for the
list
inside the expressionyeah, the docs are a bit scattered for those, there is a small section about inline aggregates in the calculation guide and the rest is in the dsl docs. But it's not that easy to discover how that works.