Skip to content

Instantly share code, notes, and snippets.

@kagemusha
Last active April 2, 2016 15:48
Show Gist options
  • Save kagemusha/8b95b93cfac710c7dd387f750432d1ed to your computer and use it in GitHub Desktop.
Save kagemusha/8b95b93cfac710c7dd387f750432d1ed to your computer and use it in GitHub Desktop.
Updating an association with Elixir Ecto
defmodule PhoenixTimeline.Game do
...
schema "games" do
belongs_to :winner, PhoenixTimeline.Player
has_many :players, PhoenixTimeline.Player
...
end
...
end
defmodule PhoenixTimeline.Player do
...
schema "players" do
...
has_one :victory, PhoenixTimeline.Game, foreign_key: :winner_id
belongs_to :game, PhoenixTimeline.Game
end
...
end
game = Repo.get Game, game_id
player = Repo.get Player, player_id
Repo.preload player, :victory #necessary?
assoc = Ecto.build_assoc(player, :victory, Map.from_struct game)
changeset = Player.changeset player, Map.from_struct assoc
Repo.update changeset
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment