Search code examples
elixirphoenix-frameworkecto

Phoenix: Ordering a query set


I'm [a noob] playing around with the Phoenix framework for fun and building a small twitter clone. I everything working, however, I want to order the tweets by the updated_at field (ascending). As you can see from tweet_controller, I have tried messing around with an order_by clause, but this did nothing for me.

Question

How do I achieve this? Within the EEx or within the tweet_controller itself?

tweet/index.html.eex

<div class="row">
  <%= for tweet <- @tweets do %>

  <h4><%= tweet.tweet %></h4>

  <% end %> 
</div>

controllers/tweet_controller.ex

...
alias TodoApp.Tweet

def index(conn, _params) do
  tweets = Repo.all(Tweet, order_by: tweet)
  render(conn, "index.html", tweets: tweets)
end
...

Solution

  • You need to use an Ecto Query:

    query = from(t in Tweet, order_by: t.updated_at)
    tweets = Repo.all(query)
    

    You may want to consider defining a function in your Tweet model for the query.

    def ordered(query) do
      from t in query,
        order_by: t.updated_at
    end
    

    You can also use the function syntax:

    def ordered(query) do
      query
      |> order_by([t], t.updated_at)
    end
    

    Then you can use this in your controller:

    tweets = Tweet |> Tweet.ordered() |> Repo.all()
    

    Here is a good post on queries: http://blog.drewolson.org/composable-queries-ecto/