shankardevy
Clarity needed on Phoenix 1.3 contexts and schema in controllers
The following code present in my controller file generated by phx.gen.html call for clarity on the intended usage of context and schema.
def index(conn, _params) do
invoices = Billing.list_invoices()
render(conn, "index.html", invoices: invoices)
end
def new(conn, _params) do
changeset = Billing.change_invoice(%InvoiceApplication.Billing.Invoice{})
render(conn, "new.html", changeset: changeset)
end
Except for the new action, where the schema %InvoiceApplication.Billing.Invoice{} is used, no part of the controller directly calls the schema. If the intention of context module is to provide public apis and hide the implementation details such as the schema name, phx.gen.html should generate a controller without specifying schema names such as Billing.new_invoice/0 or Billing.build_invoice/0.
So the clarity needed is do we expose schema outside the context or not? If we do expose them, then clearly context file is not the only public api of a context.
Most Liked
shankardevy
That’s exactly what I am proposing here. mix phx.gen.html produces the below code in the new action of controller.
changeset = Billing.change_invoice(%InvoiceApplication.Billing.Invoice{})
I am proposing that it should be
changeset = Billing.new_invoice # or build_invoice and optionally pass attrs to it.
josevalim
We do expose them outside the context. After all, Billing.list_invoice/0 returns a list of invoice structs!
PatNowak
It’s looks nice. I assume that context is keeps proper level of isolation between controller and repo & schemas. It would be logicall to hide informations about structures inside context function calls:
changeset = Billing.change_invoice(id, params)
# and it would call
Invoice.changeset(invoice_struct, params)
# where invoice_struct is
Repo.get!(Invoice, id)
Keeping this information about Invoice is redundant for controller - I already wants to change invoice, so I only wants to deal with these kind of structures.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance










