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.

Last Post!

hudsonbay

hudsonbay

Thanks

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
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
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54092 488
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 44608 311
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44167 214
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

We're in Beta

About us Mission Statement