Last active
April 2, 2016 15:48
-
-
Save kagemusha/8b95b93cfac710c7dd387f750432d1ed to your computer and use it in GitHub Desktop.
Updating an association with Elixir Ecto
This file contains 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
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