Skip to content

Commit

Permalink
belongs_to associations
Browse files Browse the repository at this point in the history
in episodes and podcasts
  • Loading branch information
electronicbites committed Dec 6, 2023
1 parent 2357144 commit 8f637fb
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 9 deletions.
7 changes: 4 additions & 3 deletions lib/radiator/podcasts/episode.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@ defmodule Radiator.Podcasts.Episode do
use Ecto.Schema
import Ecto.Changeset

alias Radiator.Podcasts.Podcast

schema "episodes" do
field :title, :string
field :podcast_id, :id

belongs_to :podcast, Podcast
timestamps(type: :utc_datetime)
end

@doc false
def changeset(episode, attrs) do
episode
|> cast(attrs, [:title])
|> cast(attrs, [:title, :podcast_id])
|> validate_required([:title, :podcast_id])
end
end
6 changes: 3 additions & 3 deletions lib/radiator/podcasts/podcast.ex
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
defmodule Radiator.Podcasts.Podcast do
use Ecto.Schema
import Ecto.Changeset
alias Radiator.Podcasts.Station

schema "podcasts" do
field :title, :string
field :hostname, :string
field :station_id, :id

belongs_to :station, Station
timestamps(type: :utc_datetime)
end

@doc false
def changeset(podcast, attrs) do
podcast
|> cast(attrs, [:title, :hostname])
|> cast(attrs, [:title, :hostname, :station_id])
|> validate_required([:title])
end
end
3 changes: 2 additions & 1 deletion test/radiator/podcasts_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ defmodule Radiator.PodcastsTest do
end

test "create_episode/1 with valid data creates a episode" do
valid_attrs = %{title: "some title"}
podcast = podcast_fixture()
valid_attrs = %{title: "some title", podcast_id: podcast.id}

assert {:ok, %Episode{} = episode} = Podcasts.create_episode(valid_attrs)
assert episode.title == "some title"
Expand Down
8 changes: 6 additions & 2 deletions test/support/fixtures/podcasts_fixtures.ex
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ defmodule Radiator.PodcastsFixtures do
attrs
|> Enum.into(%{
hostname: "some hostname",
title: "some title"
title: "some title",
station: station
})
|> Podcasts.create_podcast()

Expand All @@ -40,10 +41,13 @@ defmodule Radiator.PodcastsFixtures do
Generate a episode.
"""
def episode_fixture(attrs \\ %{}) do
podcast = podcast_fixture()

{:ok, episode} =
attrs
|> Enum.into(%{
title: "some title"
title: "my podcast episode 23",
podcast_id: podcast.id
})
|> Podcasts.create_episode()

Expand Down

0 comments on commit 8f637fb

Please sign in to comment.