The CourseTiers
naming thing was just an issue because I did that example without copypasting but it is indeed CourseTier
in my code.
Alright, I tried renaming the association to :course_tiers
but it still gives me an error. This is part of the changeset error, the one which shows the invalid changeset (and just one of the elements):
course_tier_groups: [
#Ecto.Changeset<
action: :insert,
changes: %{order: 0, tier_group_id: 14},
errors: [course_id: {"can't be blank", [validation: :required]}],
data: #LLServer.Schema.CourseTierGroup<>,
valid?: false
>,
I’ll re-post the structure as it is right now (instead of tiers I have tier groups, it was just easier to write it down but it’s the same thing):
Course schema:
schema "course" do
...
has_many(:course_tier_groups, CourseTierGroup, on_replace: :delete)
...
end
Course changeset:
def changeset(%Course{} = struct, params \\ %{}) do
struct
|> Repo.preload([:scopes, :type, :course_tier_groups])
|> cast(params, [:title, :description, :tag, :type_metadata])
|> put_scopes
|> put_type
|> cast_assoc(:course_tier_groups, with: &CourseTierGroup.changeset/2)
|> validate_required([:title, :description, :tag])
|> unique_constraint([:tag])
end
CourseTierGroup schema:
schema "course_tier_group" do
belongs_to(:course, Course)
belongs_to(:tier_group, TierGroup)
field(:order, :integer)
end
TierGroup schema:
schema "tier_group" do
...
has_many(:tiers, TierInTierGroup, on_replace: :delete)
# Won't post more, irrelevant, but this just keeps going a bit
...
end
What I pass to the changeset on create:
[%{"tier_group_id" => X, "order" => Y}, ...]
On update it works but only if I manually put the course_id
before calling the API.
Then when that is passed the course_id
property of course_tier_group
doesn’t get filled and it throws an error since the changeset is invalid.