joaquinalcerro

joaquinalcerro

Best way to handle associations in single html form

Hi everyone,

I have been learning a bit more on Ecto and Phoenix. Specifically in how to handle a master/detail o parent/child associations and the corresponding Web Form.

My question: Is there a better way to handle this typical scenario than the one I implemented below?

In my journey I read about:

  1. Ecto associations, multi, cast_assoc, put_assoc, embeded_schemas, transactions
  2. Drab Library

Checktout many resources like:

  1. Phoenix, Ecto, Drab official documentation
  2. Different Forums: Medium, Elixir Forum
  3. What’s new in Ecto 2.0
  4. Others

Adding them up and based on my understanding of some topics I came out with the following:
Scenario
Phoenix: 1.3
Elixir: 1.6.1
Ecto: 2.2.8
Schema: Invoices --> has_many --> details, belongs_to
Context name: Documents
I used basic generator to generate both

This I changed:

Invoice controller: action new

  def new(conn, _params) do
    changeset = Documents.change_invoice(
      %Invoice{
        details: [%Multipartform.Documents.Detail{}]
      }
    )
    render(conn, "new.html", changeset: changeset)
  end

Documents api:

  def add_records(%{invoice: invoice}, attrs) do
    records = 
      Enum.map(attrs["details"], fn {_, d} ->
        Map.put(d, "invoice_id", invoice.id)
      end)
      |> Enum.map(&Multipartform.Documents.Detail.changeset(
           %Multipartform.Documents.Detail{},&1)
      ) 
      |> Enum.map(fn ch -> {:ok, _d} = Repo.insert(ch) end)
    {:ok, records}
  end

  def save_invoice(invoice_changeset, attrs) do
    Multi.new()
    |> Multi.insert(:invoice, invoice_changeset)
    |> Multi.run(:add_detail, &add_records(&1, attrs))
  end

  def create_invoice(attrs \\ %{}) do
    invoice_changeset =
      %Invoice{}
      |> Invoice.changeset(attrs)

    case Repo.transaction(save_invoice(invoice_changeset, attrs)) do
      {:ok, %{invoice: invoice, add_detail: _details}} ->
        {:ok, invoice}
      {:error, _failed_operation, _failed_value, _changes_so_far} ->
        {:error, invoice_changeset}
    end 
  end

The view part is very straight forward and simplified using Drab to add more details in the UI.

Even when the Ecto documentation seemed very clear I was not able to figure out ecto cast_assoc, put_assoc and how they work together. Another challenge was understanding ecto Multi.

Can’t wait to see the @darinwilson Ecto Book.

Thanks for your comments and suggestions.

Most Liked

ekarak

ekarak

I’m describing how I’m using an Ecto.Multi to insert parent/children entities with associations in this answer:

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

Other popular topics Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement