hawkyre
Fill in `has_many` relationship while creating a new record
As it says in the title, I am trying to fill in a has_many relationship while creating a new record, but everything that I’ve been able to find requires the record to already exist before filling in the has_many.
Here’s the setup that I have:
schema "course" do
has_many(:tiers, CourseTiers)
end
schema "tier" do
has_many(:courses, CourseTiers)
end
schema "course_tiers" do
belongs_to(:course, Course)
belongs_to(:tier, Tier)
field(:order, :integer)
end
The problem comes whenever I try to create a course with the reference to the tiers in the same changeset as the new course. Since neither the course_tiers nor the course exist yet, I haven’t been able to use either build_assoc, cast_assoc, or put_assoc effectively.
Is there any workaround to this that does not involve using multi or performing the insert operation in multiple steps?
Most Liked
al2o3cr
Don’t use validate_required to verify associations; see also the docs:
Do not use this function to validate associations that are required, instead pass the
:requiredoption tocast_assoc/3orcast_embed/3.







