I’m struggling with a one-to-one mapping, I would like :monday to point to a Day, and that day should only belong to one Schedule.
defmodule Ftest.Energy.Day do
use Ecto.Schema
import Ecto.Changeset
alias Ftest.Energy.Schedule
schema "hours" do
field :hour_00, :float
field :hour_01, :float
belongs_to :schedule, Schedule
end
@doc false
def changeset(day, attrs) do
day
|> cast(attrs, [:hour_00, :hour_01, :schedule_id])
|> validate_required([:hour_00, :hour_01])
end
end
defmodule Ftest.Energy.Schedule do
use Ecto.Schema
import Ecto.Changeset
alias Ftest.Energy.Day
schema "schedules" do
has_one :monday, Day
end
@doc false
def changeset(schedule, attrs) do
schedule
|> cast(attrs, [])
|> cast_assoc(:monday)
end
end
def create_new do
Schedule.changeset(%Schedule{},
%{
monday: %{hour_00: 1.0, hour_01: 2.0}
}
) |> Repo.insert
end
If I insert using the create_new, :monday is empty.
Any help or suggestions are greatly appreciated
Solved by stackexchange, replaced has_on with belongs_to