Home > front end >  Why my optional:true option is not working in my Rails model?
Why my optional:true option is not working in my Rails model?

Time:09-27

I am struggling with the following migration:

class CreatePartnerActivationHistories < ActiveRecord::Migration[6.1]
  def change
    create_table :partner_activation_histories do |t|
      t.references :partner, null: false, foreign_key: true
      t.references :owner, null: false, foreign_key: { to_table: 'admin_users' }
  end
end

And the model:

class PartnerActivationHistory < ApplicationRecord
  belongs_to :partner
  belongs_to :owner, class_name: "AdminUser", optional: true
end

When I try to create a PartnerActivationHistory record without an owner, it raises the following error:

PG::NotNullViolation: ERROR: null value in column "owner_id" of relation "partner_activation_histories" violates not-null constraint

I can't figure it out why my optional: true is not working...

Any ideas? Thanks!

CodePudding user response:

An optional owner would mean an owner_id of nil/NULL in the database, but your spec for that column says it is mandatory and can't be null.

Remove the non-null requirement from the column like this and you should be good:

class CreatePartnerActivationHistories < ActiveRecord::Migration[6.1]
  def change
    create_table :partner_activation_histories do |t|
      t.references :partner, null: false, foreign_key: true
      t.references :owner,                foreign_key: { to_table: 'admin_users' }
  end
end

You'll want to rollback your current migration, make the change to the migration file, then migrate forward again. Assuming you're okay with losing all of the current PartnerActivationHistory records. If not, you'll need to make a new migration that just modifies that one column by removing the non-null constraint.

  • Related