I have a Review
model, which schema has belongs_to
User
notation.
Each review should belongs to user, so user_id
column is mandatory.
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> a lot of things like validate_length
|> assoc_constraint(:user)
end
And this is my migration:
defmodule MyReelty.Repo.Migrations.AddUserIdToReviews do
use Ecto.Migration
def change do
alter table(:reviews) do
add :user_id, references(:users, on_delete: :nothing)
end
create index(:reviews, [:user_id])
end
end
Unfortunately, when I'm running
%Review{} |> Review.changeset(@valid_params) |> Repo.insert!
review is saved! I double checked there is no user_id
or other user related information in details.
By the way, I checked another stuff like validate_number
it works!
Why does assoc_constraint
doesn't work in this case?
You have to add user_id
to @required_fields
, that's it