【发布时间】:2017-12-18 17:24:49
【问题描述】:
工作模式
schema "jobs" do
belongs_to :status, Test.JobStatus,
foreign_key: :status_id,
references: :id,
type: :string
timestamps()
end
我的状态模型为:
@primary_key {:id, :string, autogenerate: false}
schema "job_statuses" do
field :title, :string
field :description, :string
end
当我插入作业时,我需要输入默认作业状态(如果它不在参数中)。我知道belongs_to 关联中的默认值,但这可能是为了在您分配关系时分配默认值。谁能指出我如何为任何新创建的工作设置默认状态(假设工作状态 id 是 "acitve" 并且它已经在数据库中)。样品已经在这里https://github.com/tanweerdev/jobs
克隆项目后,只需这样做
Interactive Elixir (1.5.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Test.Jobs.create_job_status()
iex(2)> Test.Jobs.test_default_status()
(Postgrex.Error) ERROR 23502 (not_null_violation): null value in “status_id”列违反非空约束
【问题讨论】:
-
注意:如果我在迁移中添加默认值,则插入时不会出错并且状态已成功关联,但我返回给用户的变更集对象不知道更改并返回 null
status_id
标签: associations elixir phoenix-framework ecto changeset