【问题标题】:ActiveRecord::RecordInvalid: Validation failed: Users must existActiveRecord::RecordInvalid:验证失败:用户必须存在
【发布时间】:2020-07-11 03:37:15
【问题描述】:

我正在尝试从 json 文件作为项目播种 sqlite3 db。我有两个模型用户和登录名。

 require 'json'
 records = JSON.parse(File.read('db/people.json'))

 records.each do |record| 
   User.create!(record.except('logins').merge('password' => 'encrypted password'))
 end

records.each do |record|
  Login.create!(record['logins'])
end

当我运行我的 rails db:seed 时,它成功地为用户播种,然后在创建登录时失败并出现此错误 ActiveRecord::RecordInvalid: Validation failed: Users must exist 这可能与我的架构或我的种子脚本我不确定哪个

    ActiveRecord::Schema.define(version: 2020_03_30_164743) do

   create_table "logins", force: :cascade do |t|
    t.datetime "date"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "user_id"
    t.index ["user_id"], name: "index_logins_on_user_id"
   end

   create_table "users", force: :cascade do |t|
    t.string "first_name"
    t.string "last_name"
    t.string "city"
    t.string "state"
    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", null: false
     t.datetime "updated_at", null: false
     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

这是我的源代码https://github.com/jslack2537/apiDemoApp的链接

【问题讨论】:

    标签: ruby-on-rails json ruby activerecord


    【解决方案1】:

    如果您在同一个循环中编写登录名,它可能会起作用..

    records.each do |record| 
       u = User.new(record.except('logins').merge('password' => 'encrypted password'))
       u.logins = record['logins'].map{|l| Login.new(l)} 
       u.save!
     end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多