Phoenix: Ordering a query set

孤人 提交于 2019-12-12 09:42:29

问题


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
...

回答1:


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/



来源:https://stackoverflow.com/questions/33803754/phoenix-ordering-a-query-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!