Should I use Ecto.Repo in Controller or Model for Elixir Phoenix?

前端 未结 1 1974
无人共我
无人共我 2021-01-04 14:20

For some query in Controller of Phoenix, there\'re two plans for me

Plan 1:

defmodule Demo.UserController do
  # ...
  def index do
    # This is jus         


        
1条回答
  •  伪装坚强ぢ
    2021-01-04 14:56

    You should keep your Repo calls inside your controller. If your logic is complicated then you should consider moving the logic out into its own service module.

    You should treat your model functions as pure (free from side effects) so they should only act on data. So for example you could have:

    def alphabetical(query)
      order_by(query, [u], u.name)
    end
    

    But you should not have:

    def alphabetical(query)
      order_by(query, [u], u.name)
      |> Repo.all
    end
    

    This is because queries are purely data, the call to Repo.all has side effects (going off to the database) so it belongs in your controller.

    0 讨论(0)
提交回复
热议问题