Seeding users with Devise in Ruby on Rails

at. picture at. · Sep 14, 2012 · Viewed 35k times · Source

In my development and test environments, I want to seed the database with a bunch of users. I'm using Ruby on Rails v3.2.8 and the latest Devise. So I added this line in my db/seeds.rb file:

User.create(email: '[email protected]', encrypted_password: '#$taawktljasktlw4aaglj')

However, when I run rake db:setup, I get the following error:

rake aborted! Can't mass-assign protected attributes: encrypted_password

What is the proper way to seed users?

Answer

Arun Kumar Arjunan picture Arun Kumar Arjunan · Sep 14, 2012

You have to do like this:

user = User.new
user.email = '[email protected]'
user.encrypted_password = '#$taawktljasktlw4aaglj'
user.save!

Read this guide to understand what mass-assignment is: http://guides.rubyonrails.org/security.html

I am wondering why do have to directly set the encrypted password. You could do this:

user.password = 'valid_password'
user.password_confirmation = 'valid_password'