How do I change the order of the view?

hi,

I have a user view where I’m listing down the user.

def render(“user.json”, %{user: user}) do
%{
id: user.id,
name: user.name,
start_datetime: user.start_datetime,
end_datetime: user.end_datetime
}
end

I’m calling this in “index.json” and its giving me a list of user. But what I want is to give me a list of user by start_datetime order.

Can I write it in the user.json view? Will there be a query for that?

Can someone suggest me something?

Hi!

You can let the db do the sorting for you with order_by, for example: Repo.all(from u in User, order_by: u.start_datetime)

Alternatively you can use Enum.sort/2 in your “index.json” function.

2 Likes

You wouldn’t usually do this in the view as the DB is more efficient at sorting. You need a custom Ecto query, something along the lines of:

q =
      from u in User,
        order_by: [desc: :start_datetime]
Repo.all(q)

You can then use this directly in the view controller or your domain module (e.g. MyApp.Accounts.User) and call the function from your view controller.

1 Like

Thanks for this.

But this user

def render(“user.json”, %{user: user}) do
%{
id: user.id,
name: user.name,
start_datetime: user.start_datetime,
end_datetime: user.end_datetime
}
end

I’m trying to list down this in another json file

def render(“project.json”, %{project: project}) do
%{
id: project.id,
name: project.name,
users: render_many(project.users, UserView, "user.json")
}
end

In this view, I want that which you’re suggesting to me.
If I’m getting a list of user here. Is there a way to change the order of that?

I tried this

users = project.users

now users have a list of user struct
[
%User{id: 1, name: “dsasd”},
%User{id: 2, name: “sadsda”}
]
So what should I do here?

If you get the project from a regular ecto query, you can preload sorted users there. For example:

users_query = from u in User, order_by: u.start_datetime
query = from p in Project, preload: [users: ^users_query]
project = Repo.get!(query, project_id)

See https://hexdocs.pm/ecto/Ecto.Query.html#preload/3-preload-queries.

If for some reason you want to sort the users in the view:

sorted_users = Enum.sort_by(project.users, fn user -> user.start_datetime end)

I just want to sort with any key basically.

So if I have a list of users struct

[
%User{id: 1, name: “dsasd”},
%User{id: 2, name: “sadsda”}
]

Like this

I was trying something like this

users |> Enum.sort(fn d → {d.name} end)

But I’m not sure

See the last line of my reply, you need to use Enum.sort_by/3.

Yes thankyou got it