Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeding users with Devise in Ruby on Rails

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?

like image 629
at. Avatar asked Sep 14 '12 05:09

at.


People also ask

How to set up user authentication in Ruby on rails?

A step by step guide to setting up user authentication in Ruby on Rails with JWT, Devise, and Warden. Once everything is installed move into the rails project cd devise_auth_app in your ./Gemfile let’s install the required gems

What is this Ruby on rails guide for?

The guide is a short tutorial on how to create a Ruby on rails application, add some extra fields to the model. Programming since 2008. Authentication. You don’t always want your users to have faceless sessions that open your application without leaving any trace.

How to seed a Matz database using rails DB?

# db/seed.rb puts "Seeding..." User.create (name: 'Matz') User.create (name: 'DHH') puts "Seeding done." When the database already created rails db:seed would be the best option. When the database is not ready yet, in other words, we want to create the database first, then we can go with rails db:setup to first run migrations and then seeding.

What is the use of rails DB seed file?

This file is triggered by the rails db:seed command and runs in the Rails context. Which means all the model structure will be available within the file. It is also triggered by the rails db:reset and rails db:setup commands. As it is obvious from the name, the main purpose of this file is to seed the database.


2 Answers

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' 
like image 102
Arun Kumar Arjunan Avatar answered Sep 20 '22 00:09

Arun Kumar Arjunan


Arun is right. It's easier just to do this in your seeds.rb

user = User.create! :name => 'John Doe', :email => '[email protected]', :password => 'topsecret', :password_confirmation => 'topsecret' 
like image 20
George Avatar answered Sep 18 '22 00:09

George