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?
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
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.
# 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.
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.
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'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With