Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.