I think you want the following given your schema:
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:rating, :place_id])
|> validate_required([:rating]
|> assoc_constraint(:place)
end
For a :belongs_to
association, use assoc_constraint/3
for validation. It let’s Ecto check whether the Place to which the rating belongs exists. cast_assoc/3
would go on the Place schema to check Rating. Don’t use validate_required/3
to check association constraints (as instructed here).
I struggled with the different changeset validations in the same context. I outlined my findings here: Ecto Association vs Foreign Key Constraints