How to specify the order of Ecto has_many association

ecto
phoenix
#1

Howdy,

I’ve run into a bit of a roadblock and am wondering how to best handle it.

Currently I have a User schema setup with a has_many :favorite_books association. Each of these books have a ranking field. Maybe I’ve missed it, but I don’t see a way to have user.favorite_books always return them ordered according to their ranking.

I know I can order this with an Ecto query, however, as an example, when displaying them in a nested form using inputs_for I’d like the favorite books to be rendered there by their ranking too.

Thanks for any help.

0 Likes

#2

Ordering it via the query or via Enum.sort_by/2 or so are the ways that I’d do it, opting for the former when possible. :slight_smile:

0 Likes

#3

How would that look? Would you override it via the query when the favorite_books are preloaded for the User before being set in a changeset for the form?

0 Likes

#4

If the books can be globally ordered and they are not limited unless using a more detailed query then sure. If the amounts are low then joining it would be even better. Honestly I never preload, I just do another query then join them myself as I generally always want something specially done, so I just never go in the habit of calling preload manually… ^.^;

1 Like

#5

Thank you for your help with this :smile: I had it in my head that I needed to pass the sorted favorite_books into inputs_for. I’m just doing the sorting when querying for them and it is now working.

2 Likes