我[一个菜鸟]玩凤凰框架以获得乐趣并建立一个小的推特克隆。我工作的一切,但是,我想通过updated_at
字段(升序)来订购推文。正如你在tweet_controller中看到的那样,我已经尝试过使用order_by子句,但这对我没有任何帮助。
问题
我如何实现这一目标?在EEx内或tweet_controller本身内?
鸣叫/ index.html.eex
<div class="row">
<%= for tweet <- @tweets do %>
<h4><%= tweet.tweet %></h4>
<% end %>
</div>
控制器/ 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
...
答案 0 :(得分:15)
您需要使用Ecto Query:
>>> my_values = [i.get('color') for i in my_json_a]
>>> my_values
['red', 'blue']
>>>
您可能需要考虑在Tweet模型中为查询定义一个函数。
query = from(t in Tweet, order_by: t.updated_at)
tweets = Repo.all(query)
您还可以使用函数语法:
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
以下是有关查询的好帖子:http://blog.drewolson.org/composable-queries-ecto/