Last active
September 13, 2017 14:25
-
-
Save caike/a3b9969503d36ba20b2266ecc1e31eb2 to your computer and use it in GitHub Desktop.
creating nested records with cast_assoc in Phoenix
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
# In this example, Video has_many authors. | |
# Here is the code for creating a video with authors | |
# using a single call to Repo.insert | |
Enum.map([ | |
%{"title" => "Elixir", "duration" => 123, "authors" => [ | |
%{"name" => "José Valim"} | |
] | |
}, | |
%{"title" => "JavaScript", "duration" => 666, "authors" => [ | |
%{"name" => "Brendan Eich"} | |
] | |
} | |
], &Screencasts.create_video_with_author!(&1)) |
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 FireStarter.Screencasts do | |
def create_video_with_author!(attrs \\ %{}) do | |
%Video{} | |
|> Video.changeset(attrs) | |
|> Ecto.Changeset.cast_assoc(:authors) | |
|> Repo.insert! | |
end | |
end |
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 FireStarter.Screencasts.Video do | |
use Ecto.Schema | |
import Ecto.Changeset | |
alias FireStarter.Screencasts.{Video,Comment,Author} | |
schema "videos" do | |
field :duration, :integer | |
field :title, :string | |
has_many :comments, Comment | |
has_many :authors, Author | |
timestamps() | |
end | |
@doc false | |
def changeset(%Video{} = video, attrs) do | |
video | |
|> cast(attrs, [:title, :duration]) | |
|> validate_required([:title, :duration]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment