【问题标题】:Field required even though null: true必填字段,即使为空:true
【发布时间】:2023-03-11 03:50:02
【问题描述】:

我正在尝试将一些种子数据添加到我的数据库中,但 ActiveRecord 不允许我创建没有关联用户的类别。

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

当我尝试创建一个类别时:

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

我收到此错误:

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

编辑:
这是我的Category 课程:

class Category < ApplicationRecord
  belongs_to :user
  has_many :goals
end

【问题讨论】:

  • 我不是,加了Category的代码。

标签: ruby-on-rails ruby activerecord devise


【解决方案1】:

在 Rails 5 之前,belongs_to 关联的默认值是可选的。但是,对于 Rails >= 5,情况正好相反;默认情况下检查关联对象的存在。在关联上指定 :optional 以选择退出:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 2013-06-14
    • 2013-06-29
    • 2012-05-28
    • 2017-03-29
    • 2015-04-30
    • 2023-04-01
    相关资源
    最近更新 更多