Custom sorting ecto results in elixir phoenix show

By default Ecto results of a <%= for player <- @players do %> will sort by last created. My question is how to change that order, let’s say by date_created for example? Citing Ecto.Query — Ecto v3.6.1 I suppose that the code is something like this:

#lib/app/players/player.ex
  def changeset(player, attrs) do
    player
    |> order_by(asc: :date_created)
    |> cast(attrs, [:title, :description])
    |> validate_required([:title, :description])
  end

But its not workin :slight_smile:

Question N2 - Custom sorting? Example - let’s say we want our number 3 (from @players |> Enum.with_index |> Enum.map(fn({player, index}) ->) to be showed before/after other numbers - how do we do that?

Best Regards,
ykostov

The function you are showing is about changing or creating new players, not about how you query them. Your order_by should be added to whatever function you use to fetch players from the data.

1 Like

ok, thanks for your reply. So how should I query my “players”? As I understand order_by is for other things

You need to show the function returning @players

It should be something like Context.list_players()

1 Like

How are you creating @players today?

Well, its a simple resource - mix phx.gen.html

It is in the generated context that You will find a list_players function.

It is here that You can apply filtering, ordering etc.

1 Like