0

In my seed file, I made it so that the seed file will generate data for the model inside it, Adminuser. The model has the 'password_digest' column, which stores hashed passwords (using bcrypt). I am getting the table's data from a JSON file, which I parse on the seed file to make it seed on my mySQL db. The problem is, the passwords are not seeding correctly and I am getting this error:

"ActiveRecord::RecordInvalid: Validation failed: Password can't be blank, Password is too short (minimum is 6 characters)"

seeds.rb

adminuser = JSON.parse(File.read(Rails.root.join("export-admin_user.json")))
adminuser.each do |admin|
  Adminuser.create!(admin)
end

export-admin_user.json

[
    {
    "id":6,
    "username":"admin",
    "password_digest":"$2a$10$Z0tK32wRaoO4SmWl4D8vKObpaUgobb.WwS2T3mr64eZdK48/oybRm",
    "email":"sample_email1@gmail.com",
    "first_name":"admin",
    "last_name":"admin",
    "email_confirmed":true,
    "confirm_token":null,
    "created_at":"2018-03-13T02:14:34.000Z",
    "updated_at":"2018-03-13T02:14:34.000Z",
    "admin_type":"admin"
    },

    {"id":7,
    "username":"registrar",
    "password_digest":"$2a$10$hX4IlT.mn1W8fwLQ7t4JYOEz0xwuK7W1Kp655Q3doQfd08c8/ZoKm",
    "email":"sample_email2@gmail.com",
    "first_name":"registrar",
    "last_name":"registrar",
    "email_confirmed":true,
    "confirm_token":"9WhkWPT5Hhuhkimwb-F_hQ",
    "created_at":"2018-04-03T02:31:49.000Z",
    "updated_at":"2018-04-03T02:31:49.000Z",
    "admin_type":"registrar"
    }
]

I am confused as to why this error occurs. Importing the table's data by using a .sql file works, so how come this way of seeding data doesn't work?

thepersonwho
  • 85
  • 1
  • 1
  • 9
  • Can you please try the same by skipping validations. It worked for me with devise authentication. – Sajin May 09 '18 at 04:46
  • I've tried doing that by adding ".save(validate: false)" to the end of the create method ""Adminuser.create!(admin).save(validate: false)"", but it doesn't work. I'm fairly sure the error is syntax related. I'm also currently trying to fix this using the solution here: https://stackoverflow.com/questions/27931101/password-cant-be-blank-error-when-seeding-database – thepersonwho May 09 '18 at 04:57
  • 1
    Try `Adminuser.new(admin).save!(validate: false)` – Sajin May 09 '18 at 05:00

1 Answers1

1

Based on the comment given by Sajin, it turns out all I needed to do was to skip the validation when the record is being created.

The seed worked when I replaced:

Adminuser.create!(admin)

with:

Adminuser.new(admin).save!(validate: false)
thepersonwho
  • 85
  • 1
  • 1
  • 9