Reputation: 209
I currently have a table that has a field with a belongs_to relationship with another table. When I try and use Repo.insert to add a value to this field I receive an 'is_invalid' error. The error is generated by both seed file and manual command line.
The struct to insert is:
Repo.insert! %Customer_list{
age: 24,
first_name: "Tony",
last_name: "Stark",
customer_id: "D00001",
list_date: ~D[2018-09-13],
consultant_id: 8
}
The model:
defmodule InformAPI.CTL.Customer_list do
use Ecto.Schema
import Ecto.Changeset
schema "customer_lists" do
field :age, :integer
field :first_name, :string
field :last_name, :string
field :customer_id, :string
field :list_date, :date
belongs_to :consultant_id, InformAPI.CTL.Customer_list_consultants
timestamps()
end
@doc false
def changeset(customer_list, attrs) do
Customer_list
|> cast(attrs, [:customer_id, :first_name, :age, :last_name, :list_date, :consultant_id])
|> validate_required([:customer_id, :first_name, :age, :last_name, :consultant_id, ])
end
end
All fields except 'consultant_id' can be entered correctly. The 'consultant_id' is a bigint type field in the Postgres DB. The Customer_lists db has the following keys:
customer_lists_consultant_id_fkey
customer_lists_pkey
customer_lists_consultant_id_index
And the customer_lists_consultants table has:
customer_list_consultants_pkey
I'm not sure what is invalid. The consultant_id field won't accept any type of value (String, int etc).
Upvotes: 0
Views: 253
Reputation: 222198
Ecto, by default, assumes that the actual database column of a belongs_to
relationship is the name of the declaration plus "_id"
. In your case, Ecto assumed that the column's name was consultant_id_id
and so the value of consultant_id
was being ignored by cast
.
The fix is to change the name of the relationship to just consultant
.
belongs_to :consultant, InformAPI.CTL.Customer_list_consultants
Upvotes: 3