martins

martins

Setting up a many to many relationship

Hi,

I’ve read some guides and the documentation, but I have not really grokked it yet.
I’m trying to set up a many to many relationship between Cameras and Summaries.
A Summary can have one or many Cameras.

I’ve created a table like this:

  def change do
    create table(:summaries_cameras, primary_key: false) do
      add :summary_id, references(:summaries, on_delete: :delete_all)
      add :camera_id, references(:cameras, on_delete: :delete_all)
    end

    create unique_index(:summaries_cameras, [:summary_id, :camera_id])
  end

And I’ve changed both modules like this:

  schema "summaries" do
    field :name, :string

    timestamps(type: :utc_datetime)

    many_to_many :cameras, MyApp.Cameras.Camera, join_through: "summaries_cameras"
  schema "cameras" do
    field :name, :string

    timestamps(type: :utc_datetime)

    many_to_many :cameras, MyApp.Cameras.Camera, join_through: "summaries_cameras"

So far so good, but I’m struggling to understand how I associate 2 cameras with a summary.

Here I’ve started on a test:

  test "associations" do
    camera1 = camera_fixture()
    camera2 = camera_fixture()
    summary = summary_fixture()

   # Make both cameras belong to the summary
   # What to do here?
  end

Most Liked

martins

martins

I found an excellent guide at ElixirSchool that helped me assemble the pieces.

My code now looks like this:

The tests

  test "assosiations" do
    import MyApp.WizardFixtures
    import MyApp.CamerasFixtures
    alias MyApp.Wizard.Summary
    alias MyApp.Repo
    camera1 = camera_fixture()
    camera2 = camera_fixture()

    summary = summary_fixture()
    summary = Repo.preload(summary, [:cameras])
    summary_changeset = Ecto.Changeset.change(summary)

    summary_cameras_changeset = summary_changeset |> Ecto.Changeset.put_assoc(:cameras, [camera1, camera2])

    Repo.update!(summary_cameras_changeset)
    summary = Repo.reload(summary)
    summary = Repo.preload(summary, :cameras)
    assert summary.cameras == [camera1, camera2]

  end

The code

defmodule MyApp.SummaryCamera do
  use Ecto.Schema

  schema "summaries_cameras" do
    belongs_to :summary, MyApp.Wizard.Summary
    belongs_to :camera, MyApp.Cameras.Camera

    timestamps()
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> Ecto.Changeset.cast_assoc( :camera, required: true)
    |> Ecto.Changeset.cast_assoc( :summary, required: true)
  end
end

The migration:


  def change do
    create table(:summaries_cameras, primary_key: false) do
      add :summary_id, references(:summaries)
      add :camera_id, references(:cameras)
    end

    create unique_index(:summaries_cameras,
     [:summary_id, :camera_id])
  end

defmodule MyApp.Wizard.Summary do
  use Ecto.Schema
  import Ecto.Changeset

  schema "summaries" do
  
    many_to_many :cameras, MyApp.Cameras.Camera,
   join_through: "summaries_cameras"
defmodule MyApp.Wizard.Summary do
  use Ecto.Schema
  import Ecto.Changeset

  schema "summaries" do

  many_to_many :cameras, MyApp.Cameras.Camera, 
  join_through: "summaries_cameras"

Where Next?

Popular in Questions 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
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
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
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
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
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
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
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New

Other popular topics Top

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
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
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
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
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
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

We're in Beta

About us Mission Statement