您好,当我尝试创建属于用户和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
该null: false
选项有两个问题:
belongs_to
关联可以是可选的。PG::NotNullViolation: ERROR: column "user_id" contains null values
)。解:
您的表单可能发送nounou_id
为nil
或其他形式。您需要通过检查您params
的create
方法来验证这一点。
您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
。
祝好运。
@AlexandreViretti编辑已经运行的迁移是没有用的,甚至是破坏性的。您应该使用我提供的链接创建一个新的迁移,使其再次成为可选迁移,您可以接受答案并支持吗?谢谢
谢谢,它与我发布的解决方案一起使用的解决方案
不,不。您不应该在不进行迁移的情况下直接编辑架构,特别是如果您是新开发人员。如果您要复制项目,这将导致问题。遵循迁移方式。
不,我要进行新的迁移
class ChangeColumn < ActiveRecord::Migration[6.0] def change change_column :enfants, :nounou_id, :bigint, null:true end end