I have a parent and a child component. I'd like to create the parent at the same time as the child because the parent can't exist without the child. Specifically I have a subscriptions
which has_many
services
If my child model has a required field being the foreign constraint, how do I create both models at the same time? I get an error in my changeset indicating that the parent.id cannot be blank.
I know I can do Repo.insert!(Subscription)
followed by creating a Service
changeset with subscription.id
, but I was wondering if it is possible to create both at the same time?
My parent and child changesets are listed below:
Parent (Subscription)
def changeset(struct, params \\ %{}) do
# get the current time and add 30 days.
{:ok, active_until} = DateTime.utc_now()
|> DateTime.to_unix() |> Kernel.+(2592000) |> DateTime.from_unix()
struct
|> change(active_until: active_until)
|> cast(params, [:active_until, :user_id])
|> cast_assoc(:services)
|> validate_required([:active_until])
end
Child (Service)
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:start_time, :frequency, :subscription_id])
|> validate_required([:subscription_id])
|> foreign_key_constraint(:subscription_id)
end