Hello i have an issue with my app Rails when i try to create an "Enfant" who belongs to an user and a Nounou but my problem is when i create an "enfant" i'm a user with an ID but, I haven't chosen yet a nounou so i haven't got a nounou_id this is my differents code(i try to put optional: true but it doesn't work : Models and Schema
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
There are two problems with the null: false
option:
belongs_to
association could be optional.PG::NotNullViolation: ERROR: column "user_id" contains null values
).Solution:
Your form probably is sending nounou_id
as nil
or something. You need to verify that by inspecting your params
reaching your create
method.
You have made nounou_id
optional in model only but you need to run a migration to make it optional in db too where it clearly says it can't be false (null: false
).
You can take help for that migration from here.
You should modify your enfant_params
method in rails:
def enfant_params
params.require(:enfant).permit(:last_name, :first_name, :user_id, :nounou_id)
end
I am confident that this will solve your issue but if you still need help, update your question with your form code, create
action and enfant_params
and updated schema
.
Good Luck.