postgresql ruby-on-rails simple-form

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

发布于 2020-03-31 23:16:33

您好,当我尝试创建属于用户和Nounou的“孩子”时,我的应用程序Rails出现问题,但是我的问题是当我创建“孩子”时我是具有ID的用户,但是我没有还没有选择名词,所以我还没有名词ou_id,这是我的与众不同的代码(我尝试输入可选: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", precision: 6, 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", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  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.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


查看更多

提问者
Alexandre Viretti
被浏览
318
ARK 2020-01-30 18:57

null: false选项有两个问题

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

这是参考。

解:

  • 您的表单可能发送nounou_idnil或其他形式。您需要通过检查您paramscreate方法来验证这一点

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

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

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

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

祝好运。