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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment