Skip to content

Instantly share code, notes, and snippets.

@caike
Last active September 13, 2017 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caike/a3b9969503d36ba20b2266ecc1e31eb2 to your computer and use it in GitHub Desktop.
Save caike/a3b9969503d36ba20b2266ecc1e31eb2 to your computer and use it in GitHub Desktop.
creating nested records with cast_assoc in Phoenix
# 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))
defmodule FireStarter.Screencasts do
def create_video_with_author!(attrs \\ %{}) do
%Video{}
|> Video.changeset(attrs)
|> Ecto.Changeset.cast_assoc(:authors)
|> Repo.insert!
end
end
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
defmodule FireStarter.Screencasts.Author do
use Ecto.Schema
import Ecto.Changeset
alias FireStarter.Screencasts.{Video,Author}
schema "authors" do
field :name
field :email
belongs_to :video, Video
timestamps()
end
def changeset(%Author{} = author, attrs) do
author
|> cast(attrs, [:name, :email])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment