When I try to add the seed data below,
NOT NULL constraint failed:member_images.member_id:INSERT INTO "member_images"
The error appears, but I don't know why.
You can save it by setting the 0.upto(9)
part to 0.upto(8)
.
In other words, you can save foreign keys from id1 to 9 in the member_images table, but id10 and above do not save foreign keys, so it is NOT NULL constraint failed
.
This error has taken me a whole day, and I would like you to teach me.
Thank you for your cooperation.
[Table]
members
member_images (see members table)
[seed data]
names=%w (Taro Jiro Hana John Mike Sophie Bill Alex Mary Tom)
fnames=["Sato", "Suzuki", "Takahashi", "Tanaka"]
gnames=["Taro", "Jiro", "Hanako"]
affiliation=["University of Tokyo Faculty of Law", "Recruit Co., Ltd." and "Kayak"]
intros=["I want to learn programming.", "I will teach you how to learn JS effectively."]
0.upto(9)do|idx|
member = Member.create(
name —names [idx],
full_name: "#{fnames[idx%4]}#{gnames[idx%3]}",
email: "#{names[idx]}@xample.com",
birthday: "1981-12-01",
gender: [0,0,1] [idx%3],
affiliation: "#{affiliations[idx%3]}",
intro: "#{intros[idx%2]}",
administrator: (idx==0),
password: "password",
password_confirmation: "password"
)
path=Rails.root.join("db/seeds/development", "member#{idx%3+1}.jpg")
file=Rack::Test::UploadedFile.new(path, "image/jpeg", true)
MemberImage.create(
member —member,
uploaded_image:file
)
end
[Schema]
create_table "member_images", force: :cascade do | t |
t. integer "member_id", null: false
t.binary "data"
t.string "content_type"
t.datetime "created_at", null:false
t.datetime "updated_at", null:false
end
add_index "member_images", ["member_id", name: "index_member_images_on_member_id"
create_table "members", force: :cascade do | t |
t.string "name", null: false
t.string "full_name"
t.string "email"
t.date "birthday"
t. integer "gender", default:0, null:false
t.text "affiliation"
t.text "intro"
t. boolean "administrator", default: false, null: false
t.datetime "created_at", null:false
t.datetime "updated_at", null:false
t.string "hashed_password"
end
The following parts are
member = Member.create(
Try changing it like this.
member = Member.create!(
I think the reason for the error is that the member I gave you when I created the MemberImage is not saved in DB.(↓This part↓)
MemberImage.create(
member —member,
uploaded_image:file
)
Perhaps there is a validation error during Member.create.Use the create!
method to understand why you can't save an exception when there is a validation error.
© 2024 OneMinuteCode. All rights reserved.