How to order_by in phoenix 1.3

You can add a function in the Articles.Post (or something like that) module which would return the ordered results.

The index action in the controller then becomes

def index(conn, _params) do
  bydesc = Articles.Post.fetch_ordered(desc: :inserted_at) # or is it just Articles.fetch_ordered/1?
  render(conn, "index.html", bydesc: bydesc)
end

The function in Articles.Post can be something like

def fetch_ordered(constraint) do
  Post |> order_by(constraint) |> Repo.all()
end

The point of phoenix 1.3 is moving this kind of logic out of the web layer and into the domain layer, I guess. There are quite a few threads around here discussing it.

[1] How to determine contexts with Phoenix 1.3
[2] Lonestar ElixirConf 2017 - KEYNOTE: Phoenix 1.3 by Chris McCord
[3] How context should be used in phoenix 1.3?
[4] Contextual schema VS out-of-context schema (in Phoenix 1.3)
[5] Phoenix 1.3 generated folder structure
[6] Understanding contexts in Phoenix 1.3
[7] Clarity needed on Phoenix 1.3 contexts and schema in controllers
[8] Controller style & structure in Phoenix 1.3

5 Likes