Andrew Hendrie
Andrew Hendrie

Reputation: 6415

Phoenix Application 'posts' Show Newest First

In my Phoenix application I have a model called 'posts'.

Here's the relevant controller action:

  def index(conn, _params) do
    posts = Repo.all(Post)
    render(conn, "index.html", posts: posts)
  end

The problem is - this displays all posts starting with the oldest one. What I would like is to show all posts starting with the newest one (oldest one appears last).

How can I modify the controller to accomplish this?

Thanks in advance.

Upvotes: 0

Views: 45

Answers (2)

Justin Wood
Justin Wood

Reputation: 10061

You are going to want to use order_by/3.

def index(conn, _params) do
  posts = Repo.all(from Post, order_by: [desc: :inserted_at])
  render(conn, "index.html", posts: posts)
end

Upvotes: 1

Andrew Hendrie
Andrew Hendrie

Reputation: 6415

Here's a working solution I came up with from the documentation. If anyone can come up with a cleaner solution please let me know.

  def index(conn, _params) do
    posts = Repo.all(from(p in Post, order_by: [desc: :inserted_at]))
    render(conn, "index.html", posts: posts)
  end

Upvotes: 0

Related Questions