Phoenix Elixir Post JSON with association

ecto
phoenix

#1

I want to POST for association one to many with JSON in Phoenix Elixir.

My controller:
def create(conn, %{“customer” => customer_params}) do
with {:ok, %Customer{} = customer} <- Customers.create_customer(customer_params) do

My Schema:
  schema "customers" do
    field :email, :string
    field :name, :string
    has_many :contacts, App.Customers.Contact

    timestamps()
  end

  @doc false
  def changeset(customer, attrs \\ %{}) do
    customer
    |> cast(attrs, [:name, :email])
    |> validate_required([:name, :email])
    |> unique_constraint(:email)
    |> cast_assoc(:contacts, with: &App.Customers.Contact.changeset/2)
  end

The problems is:

# no function clause matching in AppWeb.CustomerController.create/2

1

%Plug.Conn{adapter: {Plug.Cowboy.Conn, :...}, assigns: %{}, before_send

2 %{“email” => “ppp”, “name” => “apples”, “phone” => “343”}


#2

The error is because the params map the controller create/2 function receives does not have a top level “customer” key as the pattern match insists on. You need to either change your controller action to:

def create(conn, customer_params) do

or else pass in the properly nested map:

%{"customer" => %{“email” => “ppp”, “name” => “apples”, “phone” => “343”}}

#3

Thanks Greg, it worked


#4

Greg, I have an observation, The data it’s insert in the customer table but field “phone” is not insert in contact table. You have something suggestion?