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.
Related
I am trying to seed my database, but I am running into this error where its telling me with_deleted is an undefined method in my seeds.rb:
User.with_deleted.each(&:really_destroy!)
User.create(
email: 'admin#example.com',
roles: [:admin],
password: 'abc123',
password_confirmation: 'abc123',
)
I believe it should have been defined from the paranoia gem. Can anyone suggest a workaround? I am working in Rails 5.1.
I tried both of these:
#user = User.create(
email: 'admin#example.com',
roles: [:admin],
password: 'abc123',
password_confirmation: 'abc123',
)
and
User.create(
email: 'admin#example.com',
roles: [:admin],
password: 'abc123',
password_confirmation: 'abc123',
)
and it looked like it worked but when I did a User.last in rails c I still got nil
As far as including act_as_paranoid in my User.rb file, this is what I have:
# acts_as_paranoid
include AddressFields
include MeAssessmentScoring
Is this not enough? But ultimately, can I just get this working without having to involve the paranoia gem? So far, what I have tried above has not worked and when I try to create a user within rails c, I get:
ActiveRecord::RecordInvalid: Validation failed: First name can't be
blank, Last name can't be blank
when I ran this: user = User.create!(email:'admin1#example.com', roles:'admin',password:'abc123', password_confirmation:'abc123')
I was able to get up and running by executing the following:
heroku pg:backups:capture
heroku pg:backups:download
pg_restore --verbose --clean --no-acl --no-owner -h localhost -U myuser -d thirdelementweb_development latest.dump
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.
I'm doing chapter 12 of hartle's tutorial. When I ran bundle exec rake db:seed I got this error:
ActiveRecord::RecordInvalid: Validation failed: Email has already been taken
I try running
rake db:reset
rake db:migrate
rake db:test:prepare
And at last
rake db:populate
but they didn't solve the problem. When I run rake db:populate it gives:
Don't know how to build task 'db:populate'
This is my seeds.rb file:
# Users
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
# Microposts
users = User.order(:created_at).take(6)
50.times do
content = Faker::Lorem.sentence(5)
users.each { |user| user.microposts.create!(content: content) }
end
# Following relationships
users = User.all
user = users.first
following = users[2..50]
followers = users[3..40]
following.each { |followed| user.follow(followed) }
followers.each { |follower| follower.follow(user) }
I guess maybe the problem is with this line email = "example-#{n+1}#railstutorial.org"
Your problem is that rake db:reset not only drops and recreates the database, but it also migrates and seeds it as well. So essentially what's happening is this:
rake db:drop
rake db:create
rake db:schema:load # (think of this as running all the migrations you've run before)
rake db:seed # (creates your 100 database users)
and then you run:
rake db:migrate # (likely unnecessary, but it causes no harm)
rake db:test:prepare # (prepares the test database)
rake db:prepare # (runs the seeds AGAIN and causes your errors)
Obviously, from this if you just stop running the rake db:prepare command your problem will go away. However, to avoid these things in the future, I strongly recommend putting a little bit of logic in your seed file. It's just Ruby, so you could wrap the User creates in an unless statement, such as:
unless User.find_by( email: "example#railstutorial.org" )
# create all 100 users
end
This will prove to be especially valuable if you have a site on production that still uses seed data (such as a SiteSetting table); you need to make sure the data makes its way into your production database, but you'll create duplicate records (or errors) running the seed again without dropping.
As an additional reference for the answer to your question, see the selected answer to this one.
I hope this provides all the information you need!
I'm doing chapter 12 of hartle's tutorial. When I ran bundle exec rake
db:seed I got this error:
ActiveRecord::RecordInvalid: Validation failed: Email has already been
taken
When you run rake db:reset, it will seed the database for you. When you then run rake db:seed, an exception will be thrown, because you are using create! in your seeds.rb file. Unlike create, create! raises an exception when the validations fail.
You can check this by running rake db:reset, and then using rails console to check your database entries.
There are a couple things you could do to prevent this, but why would you, when your data is already there?
When I run rake db:populate it gives:
Don't know how to build task 'db:populate'
Unless you define it yourself, there is no rake task named db:populate.
try using:
if the case is already existing email it will solve it.
email = "example-#{rand(100000)}#railstutorial.org"
and you can also see errors:
user = User.new(name: "Example User",
email: "example#railstutorial.org",
password: "foobar",
password_confirmation: "foobar",
admin: true,
activated: true,
activated_at: Time.zone.now)
user.errors
user.save if user.valid
Do you have both faker and populator installed in your Gemfile? That is most likely apart of the issue. Make sure you have run:
gem install populator #From the command line
and include it in your Gemfile:
gem 'populator'
Here is a link to the Git repo https://github.com/ryanb/populator/tree/master
Great article here also: http://sudharti.github.io/articles/using-faker-and-populator-rails/
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!
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).