代码之家  ›  专栏  ›  技术社区  ›  Tanweer

默认属于关联值

  •  0
  • Tanweer  · 技术社区  · 7 年前

    工作模型

    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
    

    当我插入作业时,我需要设置默认作业状态(如果不在参数中)。我知道在Bowns\u to association中有默认值,但这可能是为了在分配关系时指定默认值。任何人都可以告诉我如何为任何新创建的作业设置默认状态(假定作业状态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)错误23502(not\u null\u冲突):中的null值 列“status\u id”违反了not null约束

    2 回复  |  直到 7 年前
        1
  •  3
  •   Dogbert    7 年前

    您可以在迁移中设置默认值,并将关联字段定义为 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 read_after_writes here .

        2
  •  -1
  •   Aleksei Matiushkin    7 年前

    最适合创建状态的地方是 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