Phoenix: Request Set Request

I [noob] playing with the phoenix framework for fun and creating a small tweet clone. However, I work, but I want to order tweets in the field updated_at(ascending). As you can see from tweet_controller, I tried messing around with the order_by clause, but it did nothing for me.

Question

How do I achieve this? Inside EEx or inside 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
...
+4
source share
1 answer

You need to use Ecto Query :

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

You might want to consider defining a function in your Tweet model for the request.

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

:

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

:

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

: http://blog.drewolson.org/composable-queries-ecto/

+15

Source: https://habr.com/ru/post/1616535/


All Articles