Search code examples
ruby-on-railsrubyactiverecorddevise

Field required even though null: true


I'm trying to add some seed data to my database, but ActiveRecord won't let me create a category without an associated user.

ActiveRecord::Schema.define(version: 2020_07_18_233635) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "categories", force: :cascade do |t|
    t.string "name"
    t.bigint "user_id"
    t.string "image_url"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["user_id"], name: "index_categories_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

  add_foreign_key "categories", "users"
  add_foreign_key "goals", "categories"
end

When I try to create a category:

category = Category.create!({name: 'Fitness', image_url: 'some_url'})

I get this error:

ActiveRecord::RecordInvalid (Validation failed: User must exist)

EDIT:
Here's my Category class:

class Category < ApplicationRecord
  belongs_to :user
  has_many :goals
end

Solution

  • Prior to Rails 5, the default for a belongs_to association was that it was optional. However, for Rails >= 5, the reverse is true; the presence of an associated object is checked by default. Specify :optional on the association to opt out of that:

    class Category < ApplicationRecord
      belongs_to :user, optional: true
      has_many :goals
    end