bundle exec rake db:populate >> rake aborted - Validation failed - ruby-on-rails

I'm currently going through the RoR guides, and i'm stuck at...
"Adding following/follower relationships to the sample data."
Here's the code that is suppose to work: sample_app/lib/task/sample_data.rake
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
make_users
make_microposts
make_relationships
end
end
def make_users
admin = User.create!(name: "Example User2",
email: "example2#railstutorial.org",
password: "foobar",
password_confirmation: "foobar")
admin.toggle!(:admin)
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}#railstutorial.org"
password = "password"
User.create!(name: name,
email: email,
password: password,
password_confirmation: password)
end
end
def make_microposts
users = User.all(limit: 6)
50.times do
content = Faker::Lorem.sentence(5)
users.each { |user| user.microposts.create!(content: content) }
end
end
def make_relationships
users = User.all
user = users.first
followed_users = users[2..50]
followers = users[3..40]
followed_users.each { |followed| user.follow!(followed) }
followers.each { |follower| follower.follow!(user) }
end
when i do rake db:reset my database reset with no problems.
when i do rake db:populate an error occurred stating this:
rake aborted!
Validation failed: Follower can't be blank`
so i checked my database, and all tables were populated except for "relationships" table.. any thoughts or suggestions? I'm pretty sure there's a problem with the code, def making_relationships, to be exact. hope anyone has a solution to this..
-Marc

Since you're calling .create! on models like User and Micropost (user.microposts), it is one of them throwing the error mentioned.
Please, post the code for these models to enable us answer more specifically.
You can still debug the problem by yourself though. Just hit rails c in the projects root directory, and try to create instances with the very same attributes you're trying in rake task:
$ rails c
$ user = User.create!(name: name,
email: email,
password: password,
password_confirmation: password)
$ micropost = user.microposts.create!(content: "Hello, cruel world!")
# by this step you should already see some errors raised; if that's not sufficient,
# call the following methods to figure out what model suffers the validation error
user.errors.full_messages
micropost.errors.full_messages
Anyway, it's the validation that's not satisfied. Double check you're passing all required attributes passed when creating a model with a shebang create!. Specifically check which model requires presence of Follower (whatever that is).

Related

"Email has already been taken" error on db:seed

I am running through Hartl's Rails tutorial, but when I try to seed Microposts I am getting the error: "ActiveRecord::RecordInvalid: Validation failed: Email has already been taken"
I did db:migrate:reset followed by db:seed which throws up the error. Is there something wrong with what I am trying to seed?
User.create!(name: "Example User",
email: "example#railstutorial.org",
password: "foobar",
password_confirmation: "foobar",
admin: true,
activated: true,
activated_at: Time.zone.now)
99.times do |n|
name= Faker::Name.name
email = "example-#{n+1}#railstutorial.org"
password = "password"
User.create!(name: name,
email: email,
password: password,
password_confirmation: password,
activated: true,
activated_at: Time.zone.now)
end
users = User.order(:created_at).take(6)
50.times do
content = Faker::Lorem.sentence(word_count: 5)
users.each { |user| user.microposts.create!(content: content) }
end
You have probably already created some records in the database, which invokes validation. To check this, run the console rails c and then type User.first.
If you have some records run rake db:reset to reset database.
If you want to be able to run the seed multiple times, write
User.find_or_create_by(email: email) do |u|
u.name: name,
u.password: password,
u.password_confirmation: password,
u.activated: true,
u.activated_at: Time.zone.now
end
instead your code.
Instead of create! user create so if the email address is already taken, the record would not be created and the script gracefully continues, and you won't get an exception.
I'm not sure what exactly happened but I went ahead and reset my migrations once more and when I reseeded it worked. So if anyone else has this problem in the future, just clear the database again and try again.
In my case I had a syntax error when calling Rake :: .....
It worked for me to update the gem with gem 'faker', '~> 2.15', '> = 2.15.1'
Then rails db: migrate: reset and rails db: seed.

Devise user created with Rails generator cannot sign in

I'm working on a Rails Engine which will depend on Devise.
I created an installer using Rails generator which you can find here. The installer creates the first credentials in order to access the administration panel later.
The problem is that I cannot sign in with those credentials. Weirdly then, if I delete the account and recreate it via Rails console, they do work. I think that's due to something happening during the installer.
Here a snippet of it:
# Binda installer generator ...
def setup_devise
return if Rails.env.production?
# Copy the initilializer on the application folder
template 'config/initializers/devise.rb'
# Add secret key
inject_into_file 'config/initializers/devise.rb', after: "config.secret_key = '" do
SecureRandom.hex(64)
end
# Add pepper
inject_into_file 'config/initializers/devise.rb', after: "config.pepper = '" do
SecureRandom.hex(64)
end
# some other code for mailer ...
end
def create_credentials
#username = ask("What's your email? ['mail#domain.com']").presence || 'mail#domain.com'
#password = ask("What's your password? ['password']").presence || 'password'
Binda::User.create( email: #username, password: #password, password_confirmation: #password )
# Binda installer generator continue ...
Here the full code.
More info
I found out that even if I modify devise.rb file the new configuration is not loaded until the end of the installer. This means the new salt/pepper isn't considered while creating the first user. How can I reload it before running the create_credentials method?
Sorted!
The problem is that if you add salt/pepper configuration to the devise.rb of your application you need to reload the environment before being able to create a user with the new settings.
To do that I moved the user creation into a task. This way the installer to reload the environment (and Devise config as weel) and is able to set the encrypted password correctly.
Installer
# lib/generators/myEngine/install/install_generator.rb
def create_credentials
rake 'binda_create_initial_user'
end
Task
# lib/tasks/binda.rake
desc "Create initial user"
task :binda_create_initial_user => :environment do
username = 'mail#domain.com'
password = 'password'
Binda::User.create!( email: username, password: password, password_confirmation: password )
end
If you want to keep asking for mail and password:
# lib/tasks/binda.rake
desc "Create first user"
task :binda_create_initial_user => :environment do
STDOUT.puts "What is your email? [mail#domain.com]"
username = STDIN.gets.strip
username = 'mail#domain.com' if username.blank?
STDOUT.puts "What is your password? [password]"
password = STDIN.gets.strip
password = 'password' if password.blank?
Binda::User.create!( email: username, password: password, password_confirmation: password )
end

seeding db with users using devise fails: ActiveRecord::RecordInvalid: Validation failed: Email is invalid

I am trying to run a simple loop to create multiple seed users:
In seeds.rb:
5.times do
user = User.new(
email: RandomData.random_space_email,
password: 'teatea',
password_confirmation: 'teatea'
)
user.skip_confirmation!
user.save!
end
RandomData.random_space_email:
def self.random_space_email
"#{##names.sample}##{##space_words.sample}.#{##space_words.sample}"
end
When I run rake db:reset I get this error: ActiveRecord::RecordInvalid: Validation failed: Email is invalid
however if I set the loop to run only once (1.times do) everything works as expected.
Any help would be wonderful!
After carefully checking:
def self.random_space_email
"#{##names.sample}##{##space_words.sample}.#{##space_words.sample}"
end
I found that ##space_words sometimes contains strings with spaces... and this seems to be causing devise to throw an error, as there cannot be whitespace in an email address.

How do I manually change/update a user password in devise 3.2.x?

I tried to do this from my seeds.rb:
user = User.find_or_create_by email: ENV['ADMIN_EMAIL'].dup, password: ENV['ADMIN_PASSWORD'].dup, password_confirmation: ENV['ADMIN_PASSWORD'].dup
I am getting this error message:
PG::UndefinedColumn: ERROR: column users.password does not exist
LINE 1: ...sers" WHERE "users"."email" = 'abc#test.com' AND "users"."p...
I tried encrypted_password, but then I get the same for users.encrypted_password_confirmation does not exist.
Thoughts on the best way to do this?
I would just go into the Rails console (rails c)
user = User.new(email: "myemail.com", password: "superSecret")
user.save
You can also change it
user = User.find_by_email("myemail.com")
user.password = "newSuperSecret"
user.save
EDIT:
I just put my first block of code in my seed.rb and ran rake db:seed with no problem. So I think the crux of your problem is just having the password attribute in your find_or_create_by call. I think if you put this in your seed.rb you'll get the results you want (although I have to admit I'm not certain about the environment variables working, you might have to retool that portion of it).
user = User.find_or_create_by(email: ENV['ADMIN_EMAIL'].dup)
user.password = ENV['ADMIN_PASSWORD'].dup if user.encrypted_password.blank?
user.save!

error while running rake db:populate

after running rake db:reset
i rund rake db:populate and i'm getting this error don't know where it's coming from
rake aborted!
undefined method `+' for 4..5:Range
Tasks: TOP => db:populate
(See full trace by running task with --trace)
in my task folder
namespace :db do
desc " Fill database with sample data"
task populate: :environment do
admin = User.create!(name: "Emple User",
email: "exampel#railstuttorial.org",
password: "password",
password_confirmation: "password")
admin.toggle!(:admin)
99.times do |n|
name = Faker::Name.name
email = "example-#{n + 1}#railstutorial.org"
password = "password"
User.create!(name: name, email: email, password: password,
password_confirmation: password)
end
users = User.all(limit: 6)
50.times do
content = Faker::Lorem.sentence(4..5)
users.each { |user| user.microposts.create!(content: content) }
content = nil
end
end
end
You are passing a range to Faker::Lorem.sentence in your 50.times loop.
I'm not sure what you're trying to achieve but that method is expecting an integer (did you mean 4 or 5?) and when it tries to add something to it within the Faker::Lorem code it is causing that error.

Resources