默认 belongs_to 关联值

Default belongs_to association value

工作模式

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

After cloning the project, just do this

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 column "status_id" violates not-null constraint

创建状态的最合适位置是在您的 Job.changeset/2 回调中:

  @doc false
  def changeset(%Job{} = job, attrs) do
    job
    |> cast(attrs, @fields)
    |> validate_required(...)
    |> create_and_put_default_status() # ⇐ HERE
    |> ...
  end

create_and_put_default_status() 的实现符合以下规范:

@spec create_and_put_default_status(Plug.Conn.t) :: Plug.Conn.t

您可以将默认值放在迁移中并将关联字段定义为read_after_writes: true。这将确保在插入记录后,将从数据库中读回该字段,这将解决您在评论中提到的问题,即成功插入记录后该字段仍然 nil

belongs_to :status, Test.JobStatus,
  foreign_key: :status_id,
  references: :id,
  type: :string,
  define_field: false

field :status_id, :integer, read_after_writes: true

查看文档以了解有关 define_field here and read_after_writes here 的更多详细信息。