Skip to content

Instantly share code, notes, and snippets.

@caike caike/a-seeds.exs
Last active Sep 13, 2017

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