How to apply field based sorting on many-to-many relationships?

I have a resource called Post, which has a many-to-many relationship with the Tag resource. My relationship in the Post resource is defined as follows:

  many_to_many :tags, Tag do
    through TagPost
    source_attribute_on_join_resource :post_id
    public? true
  end

Whenever I load Tag data for a Post, I want the loaded tag data to be sorted based on a text attribute from the Tag resource. I have added the below line on the association in my post resource. When I tried the below, the SQL order_by text was applied to each individual Tag rather than for the whole data. I keep getting the tags in different orders each time I load.

sort text: :asc

If the above method won’t work, Is there a way to sort the tags while using Ash.load?

For example, in my action, I’m loading the tag data for my Post resource as follows:

Ash.load(post, [:tags])

How can I add a sort here?

Ash.load(post, tags: Ash.Query.sort(Tag, text: :ask))

Thank you for your reply. However, this sorting is not working in the Ash JSON API. I sent a POST request to this action, but the tags are not getting sorted in the response; they keep shuffling. For your information, it is sorting correctly within the action.

:wave: correct, the includes that are applied in the action are not used by the API. In general, I suggest not loading data inside the action, but letting each caller request what they need. This avoids double loading data for cases where an API extension (i.e AshJsonApi or AshGraphql uses that action).

For your specific request, there was not a good way to sort included data, so I added one. It will be available in the next release. A (short) guide is available here.

It looks like this in practice:

/your/endpoint?include=tags&sort_included[tags]=text