hudsonbay

hudsonbay

Phoenix controller and views for bulk insert

Hi, I am trying to create a POST endpoint in Phoenix that will receive an array of maps %{} and I need to insert all of that data into a database as a bulk insertion.

It would be receiving something like this:

entries = [                                                                                                                                   
     %{name: "Frank", age: 23},                                                        
     %{name: "John", age: 24}                                                                                               
   ]

Parameters look like this:

%{"data" => [%{"name" => "Frank", "age" => 23}, %{"name" => "John", "age" => 24}]}

For now I only have created the Repo functions like:

def create_users(attrs) do
    User
    |> Repo.insert_all(attrs)
  end

I’ve searched the entire web and I can’t find any article that explains how the controllers and views should be.

I know this is incorrect because it doesn’t work but it’s more or less what I have right now :frowning:

def create_many(conn, %{"data" => users_params}) do
    case Users.create_users(users_params) do
      {:ok, %{errors: _, rows_affected: _}} ->
        conn
        |> json(%{result: "ok"})
        # render(conn, "bulk_creation_result.json", %{some: result})

      # {:error, _, changeset, _} ->
      #   render(conn, MyApp.ChangesetView, "error.json", changeset: changeset)
    end

As far as the views I really have no clue :frowning:

Does someone have done this yet in the past and could show me a correct example?

Thanks in advance

Marked As Solved

jhefreyzz

jhefreyzz

Does Entries have relationship with User model? If so, you can pass cast_assoc to your changeset pipeline to do bulk insertion.

What do you intent to do with views? Do you want to display the returned data?
When generating a json api using mix phx.gen.json it generates similar to this:

  def render("index.json", %{contacts: contacts}) do
    %{data: render_many(contacts, ContactView, "contact.json")}
  end

  def render("show.json", %{contact: contact}) do
    %{data: render_one(contact, ContactView, "contact.json")}
  end

 def render("phone_number.json", %{number: number}) do
    %{id:  number.id, phone_number: number.phone_number}
 end

 def render("contact.json", %{contact: contact}) do
    %{id: contact.id,
       name: contact.name,
       phone_numbers: render_many(contact.numbers, ContactView, "phone_number.json")
    }
end

Make sure you know the shape of the returned data so you can structure the views.

Given the results:

[
 %Contact{
   id: 'something',
   name: 'some name',
   numbers: [
      %Number{id: 'some id', phone_number: 'some phone number'},
      %Number{id: 'some id', phone_number: 'some phone number'}
   ]
 },
%Contact{
   id: 'something',
   name: 'some name',
   numbers: [
      %Number{id: 'some id', phone_number: 'some phone number'},
      %Number{id: 'some id', phone_number: 'some phone number'}
   ]
 }
]

We can return its json format response like this:

with {:ok, entries} = Users.create_users(users_params) do
        conn
        |> render("contact.json", contact: entries)
end

Be sure to put an action_fallback to your controller so it can automatically handle changeset errors.

In the example I gave, it uses ContactView, in your case change the view name to your appropriate one.

Where Next?

Popular in Questions Top

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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
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
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement