无法将 Repo.Insert 值放入 belongs_to 字段
Unable to Repo.Insert a value into a belongs_to field
我目前有一个 table,它有一个字段与另一个 table 有 belongs_to 关系。当我尝试使用 Repo.insert 向该字段添加值时,我收到 'is_invalid' 错误。错误是由种子文件和手动命令行产生的。
要插入的结构是:
Repo.insert! %Customer_list{
age: 24,
first_name: "Tony",
last_name: "Stark",
customer_id: "D00001",
list_date: ~D[2018-09-13],
consultant_id: 8
}
型号:
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
除了'consultant_id'之外的所有字段都可以正确输入。 'consultant_id' 是 Postgres 数据库中的 bigint 类型字段。 Customer_lists 数据库具有以下键:
customer_lists_consultant_id_fkey
customer_lists_pkey
customer_lists_consultant_id_index
而 customer_lists_consultants table 有:
customer_list_consultants_pkey
我不确定什么是无效的。 consultant_id 字段不接受任何类型的值(字符串、整数等)。
Ecto 默认假定 belongs_to
关系的实际数据库列是声明名称加上 "_id"
。在您的情况下,Ecto 假定列的名称是 consultant_id_id
,因此 consultant_id
的值被 cast
.
忽略
解决方法是将关系名称更改为 consultant
。
belongs_to :consultant, InformAPI.CTL.Customer_list_consultants
我目前有一个 table,它有一个字段与另一个 table 有 belongs_to 关系。当我尝试使用 Repo.insert 向该字段添加值时,我收到 'is_invalid' 错误。错误是由种子文件和手动命令行产生的。
要插入的结构是:
Repo.insert! %Customer_list{
age: 24,
first_name: "Tony",
last_name: "Stark",
customer_id: "D00001",
list_date: ~D[2018-09-13],
consultant_id: 8
}
型号:
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
除了'consultant_id'之外的所有字段都可以正确输入。 'consultant_id' 是 Postgres 数据库中的 bigint 类型字段。 Customer_lists 数据库具有以下键:
customer_lists_consultant_id_fkey
customer_lists_pkey
customer_lists_consultant_id_index
而 customer_lists_consultants table 有:
customer_list_consultants_pkey
我不确定什么是无效的。 consultant_id 字段不接受任何类型的值(字符串、整数等)。
Ecto 默认假定 belongs_to
关系的实际数据库列是声明名称加上 "_id"
。在您的情况下,Ecto 假定列的名称是 consultant_id_id
,因此 consultant_id
的值被 cast
.
解决方法是将关系名称更改为 consultant
。
belongs_to :consultant, InformAPI.CTL.Customer_list_consultants