Last active
July 6, 2016 17:19
-
-
Save daveshah/61d800864ddf5e9c1a638f663d510d11 to your computer and use it in GitHub Desktop.
TIL: Ecto 2.0 many_to_many
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 1) Created User and Run models first (generated) | |
# 2) Created the UserRun model (generated) then removed all but Ecto.Schema | |
# 3) Corrected the UserRun model so that it looked like this: | |
defmodule Gatherto.UserRun do | |
use Ecto.Schema | |
schema "users_runs" do | |
belongs_to :user, Gatherto.User #this was VERY important! Before I had field :user_id, :binary_id | |
belongs_to :run, Gatherto.Run #this was VERY important! Before I had field :run_id, :binary_id | |
timestamps() | |
end | |
end | |
#From there I could - not sure if this is AOK (can I just use build_assoc ?) | |
dave = Repo.all(User) |> Repo.preload(:runs) |> List.first | |
run = Repo.all(Run) |> List.first | |
changeset = Ecto.Changeset.change(dave) |> Ecto.Changeset.put_assoc(:runs, [run]) | |
Repo.update(changeset) | |
#(This seemed not to work) | |
assoc = Ecto.build_assoc(dave, :runs, title: "Super cool", description: "Fast and long") | |
Repo.insert(assoc) | |
#In the above case a new Run gets created but is not associated with the user. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So, maybe the way to get all of this in a nicer place would be to expose User.changeset_with_run(user, run) ?