Search code examples
associationselixirphoenix-frameworkectochangeset

Default belongs_to association value


Job Model

schema "jobs" do
  belongs_to :status, Test.JobStatus,
    foreign_key: :status_id,
    references: :id,
    type: :string
  timestamps()
end

and I have a status Model as:

@primary_key {:id, :string, autogenerate: false}
schema "job_statuses" do
  field :title, :string
  field :description, :string
end

When I am inserting the job I need to put default job status(if its not in params). I know about defaults in belongs_to association but this thing is for perhaps to assign default values when you are assiging a relationship. Can any one point me how I can put default status for any newly created job(assumed job status id is "acitve" and its already in the database ) . sample is already here 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


Solution

  • You can put the default in the migration and define the association field to be read_after_writes: true. This will ensure that after inserting the record, that field will be read back from the database which will fix the problem you mentioned in your comment that the field was still nil after inserting the record successfully.

    belongs_to :status, Test.JobStatus,
      foreign_key: :status_id,
      references: :id,
      type: :string,
      define_field: false
    
    field :status_id, :integer, read_after_writes: true
    

    Check out the documentation for more details about define_field here and read_after_writes here.