创建表单(简单表单)的问题PG :: NotNullViolation:错误:Rails列中的空值

您好,当我尝试创建属于用户和Nounou的“孩子”时,我的应用程序Rails出现问题,但是我的问题是当我创建“孩子”时我是具有ID的用户,但是我还没有选择名词ou,所以我还没有名词no_id,这是我的不同代码(我尝试输入optional:true,但是不起作用: 模型和架构

class Enfant < ApplicationRecord
  belongs_to :user
  belongs_to :nounou,optional: true
end


class Nounou < ApplicationRecord
  has_many :enfants
end


class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable,:lockable,:timeoutable,:trackable and :omniauthable
  devise :database_authenticatable,:registerable,:recoverable,:rememberable,:validatable
  has_many :enfants
end


  create_table "enfants",force: :cascade do |t|
    t.string "last_name"
    t.string "first_name"
    t.bigint "nounou_id",null: false
    t.bigint "user_id",null: false
    t.datetime "created_at",precision: 6,null: false
    t.datetime "updated_at",null: false
    t.index ["nounou_id"],name: "index_enfants_on_nounou_id"
    t.index ["user_id"],name: "index_enfants_on_user_id"
  end

  create_table "nounous",force: :cascade do |t|
    t.string "name"
    t.integer "price"
    t.string "localisation"
    t.integer "evaluation"
    t.integer "places"
    t.string "first_name"
    t.string "last_name"
    t.string "photo"
    t.datetime "created_at",null: false
  end

  create_table "users",force: :cascade do |t|
    t.string "email",default: "",null: false
    t.string "encrypted_password",null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at",null: false
    t.string "username"
    t.string "photo"
    t.string "first_name"
    t.string "last_name"
    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

end


kangbowen004 回答:创建表单(简单表单)的问题PG :: NotNullViolation:错误:Rails列中的空值

null: false选项存在两个问题:

  • 它不认为belongs_to关联是可选的。
  • 如果数据库中已经有记录,则由于没有默认值(在PostgreSQL,PG::NotNullViolation: ERROR: column "user_id" contains null values中),运行迁移将生成异常。

Here's the reference.

解决方案:

  • 您的表单可能正在以nounou_id的形式发送nil。您需要通过检查您的params是否达到create方法来进行验证。

  • 您仅在模型中将nounou_id设置为可选,但是您需要运行迁移以使其在db中也可选,因为它清楚地表明它不能为假(null: false)。 您可以从here获得有关迁移的帮助。

  • 您应该在rails中修改enfant_params方法:

def enfant_params
  params.require(:enfant).permit(:last_name,:first_name,:user_id,:nounou_id)
end

我相信这可以解决您的问题,但是,如果您仍然需要帮助,请使用表单代码,create操作和enfant_params并更新schema来更新您的问题。

祝你好运。

,

非常感谢我的迁移文件中的内容:t.bigint "nounou_id" t.bigint "user_id",null: false
我为nullou_id删除了null:false,并且有效;)

本文链接:https://www.f2er.com/2692147.html

大家都在问