I want to populate the database with a number of stores and users, that each user corresponds to one store. The issue with the code below is that I get the error Validation failed: Email has already been taken.
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
make_stores
make_users
end
end
def make_stores
50.times do
name = Faker::Company.name
manager = Faker::Name.name
address = Faker::Address.street_name
Store.create!(name: name,
manager: manager,
address: address)
end
end
def make_users
stores = Store.all(limit: 8)
99.times do |n|
first_name = Faker::Name.first_name
last_name = Faker::Name.last_name
email = "example-#{n+1}#example.org"
password = "password"
stores.each { |store| store.users.create!(first_name: first_name,
last_name: last_name,
email: email,
password: password,
password_confirmation: password) }
end
end
The problem is that you're setting the email variable before calling stores.each, so all 8 stores will get a user with the same email.
Do something like this instead:
def make_users
stores = Store.all(limit: 8)
99.times do |n|
password = "password"
stores.each do |store|
first_name = Faker::Name.first_name
last_name = Faker::Name.last_name
email = "#{store.name.parameterize}-#{n+1}#example.org"
store.users.create!(first_name: first_name,
last_name: last_name,
email: email,
password: password,
password_confirmation: password)
end
end
end
Now the first 8 users will have an email like (some-store-name)-1#example.org, next 8 will have (some-store-name)-2#example.org and so on.
Related
I want to create dozens of logins that rely on data from this array, logins:
logins = [
{
email: Faker::Internet.email,
password: "password",
first_name: Faker::Name.first_name,
last_name: Faker::Name.last_name
},
{
email: Faker::Internet.email,
password: "password",
first_name: Faker::Name.first_name,
last_name: Faker::Name.last_name
}
]
What is a better way of writing this array rather than copy and pasting that hash dozens of times? I am familiar with x.times do but that wouldn't work on an array.
Here's the code where I pass in the logins:
logins.each do |login|
li = LoginInformation.new(login: login[:email], password: login[:password])
if UserManager.save(li)
company_ids.each do |id|
li.contacts.create(first_name: login[:first_name], last_name: login[:last_name], email_address: login[:email], company_id: id, is_employee: true)
end
end
end
One way to simplify the creation of your logins array is to pass the hash object with the included Faker methods as a block, like so:
logins = Array.new(10) { { email: Faker::Internet.email, password: 'password', first_name: Faker::Name.first_name, last_name: Faker::Name.last_name } }
You can replace the 10 in this example with the number of elements required for your use case.
Hope this helps!
.times returns an enumerator that you can call .map on to get an array.
logins = 10.times.map do
{
email: Faker::Internet.email,
password: "password",
first_name: Faker::Name.first_name,
last_name: Faker::Name.last_name
}
end
Or use Array.new as mentioned by Zoran Pesic.
You can use for loop to insert the values multiple times
logins=[]
for i in 0..10
logins <<
{
email: Faker::Internet.email,
password: "password",
first_name: Faker::Name.first_name,
last_name: Faker::Name.last_name
}
end
Can do this way also:
10.times do
login = { email: Faker::Internet.email, password: 'password', first_name: Faker::Name.first_name, last_name: Faker::Name.last_name }
li = LoginInformation.new(login: login[:email], password: login[:password])
if UserManager.save(li)
company_ids.each do |id|
li.contacts.create(first_name: login[:first_name], last_name: login[:last_name], email_address: login[:email], company_id: id, is_employee: true)
end
end
end
None of the data in seeds.rb is loaded into the development db. There is no error message. How can I determine the cause?
If I run rake:db:migrate:reset it just runs and produces no error messages. The if I go to the console, run User.first, it says nil. Also I downloaded the development db and there are no records in it (tables are created correctly, just no records).
Is there some way to trace the cause?
Part of seeds.rb:
User.create!(fullname: "Example User",
username: "fakename0",
email: "example#railstutorial.org",
admin: true,
activated: true,
activated_at: Time.zone.now,
password: "foobar",
password_confirmation: "foobar")
User.create!(fullname: "Example User 2",
username: "fawwkename0",
email: "exaaample#railstutorial.org",
admin: false,
activated: true,
activated_at: Time.zone.now,
password: "foobar",
password_confirmation: "foobar")
99.times do |n|
fullname = Faker::Name.name
username = "fakename#{n+1}"
email = "example-#{n+1}#railstutorial.org"
password = "password"
User.create!(fullname: fullname,
username: username,
email: email,
password: password,
password_confirmation: password,
activated: true,
activated_at: Time.zone.now)
end
Message.create!(email: "example#example.com",
name: "Example User",
content: "This is my message")
Organization.create!(org_name: "Fictious business",
bio: "The background of the organization here",
actioncode: 111)
99.times do |n|
org_name = Faker::Company.name
bio = Faker::Lorem.paragraph(2)
actioncode = Faker::Number.number(3)
Organization.create!(org_name: org_name,
bio: bio,
actioncode: actioncode)
end
Member.create!(organization_id: rand(1..100),
email: "me#example.com",
username: "fake-name0",
fullname: Faker::Name.name,
activated: 1,
activated_at: Time.zone.now,
password: "foobar",
password_confirmation: "foobar")
99.times do |n|
organization_id = rand(1..100)
email = "rails0-#{n+1}#example.com"
username = "fake-name#{n+1}"
fullname = Faker::Name.name
activated = rand(0..1)
activated_at = Faker::Date.backward(14) if activated==1
password = "foobar"
password_confirmation = "foobar"
Member.create!(organization_id: organization_id,
email: email,
username: username,
fullname: fullname,
activated: activated,
activated_at: activated_at,
password: password,
password_confirmation: password_confirmation)
end
To load db/seeds.rb you need to run rake db:seed.
When I run db:populate, it gives the following error :
Validation failed: Email has already been taken, Nyaaid has already been taken
The email should be unique and the ID should be unique! Here's the validation for the nyaaid :
VALID_NYAAID_REGEX = /NYAA\/(N|O)\/(NP|WP|SP|CP|EP|NCP|UP|SGP|NWP)\d{4}\z/i
validates :nyaaid, format: { with: VALID_NYAAID_REGEX }, uniqueness: { case_sensitive: false }
Here's the Faker code, sample_data.rake :
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
Awardunit.create!(nyaaid: "NYAA/N/WP0001", name: "Test Unit", address: "No. 50, Kalpitiya Road, Maradana", district: "Colombo", contact: ["23232223"], email: "abc#localhost.com", insthead: "Namal Kaluaarachchi", instheadcontact: ["324234234"], datestarted: "1/10/2013", allowedmem: "5", remarks: "")
#districts = ['Ampara', 'Anuradhapura', 'Badulla', 'Batticaloa', 'Colombo', 'Galle', 'Gampaha', 'Hambantota', 'Jaffna', 'Kalutara', 'Kandy', 'Kegalle', 'Kilinochchi', 'Kurunegala', 'Mannar', 'Matale', 'Matara', 'Moneragala', 'Mullaitivu', 'Nuwara Eliya', 'Polonnaruwa', 'Puttalama', 'Ratnapura', 'Trincomalee', 'Vavuniya']
#allowedmem = Array(5..20)
#from = 10.years.ago
#to = Time.now
def rand_date
Time.at(#from + rand * (#to.to_f - #from.to_f)).strftime("%d/%m/%Y")
end
#idarray = Array(2222..9999)
def pickidarray
id = #idarray.sample
#idarray.delete(id)
return id
end
50.times do |n|
nyaaid = "NYAA/N/WP#{pickidarray}"
name = Faker::Company.name
address = Faker::Address.street_address
district = #districts.sample
contact = Faker::PhoneNumber.phone_number
email = "example-#{n+1}#slnyaa.org"
insthead = Faker::Name.name
instheadcontact = Faker::PhoneNumber.phone_number
datestarted = rand_date
allowedmem = #allowedmem.sample
remarks = Faker::Lorem.paragraphs(rand(1..2))
Awardunit.create!(nyaaid: nyaaid, name: name, address: address, district: district, contact: contact, email: email, insthead: insthead, instheadcontact: instheadcontact, datestarted: datestarted, allowedmem: allowedmem, remarks: remarks)
end
end
end
just try
Awardunit.create!(nyaaid: "NYAA/N/WP0001", name: "Test Unit", address: "No. 50, Kalpitiya Road, Maradana", district: "Colombo", contact: ["23232223"], email: "abc#localhost.com", insthead: "Namal Kaluaarachchi", instheadcontact: ["324234234"], datestarted: "1/10/2013", allowedmem: "5", remarks: "")
add Awardunit.destroy_all before creating first object.
Here are my factories:
Users.rb
FactoryGirl.define do
sequence(:email) do |n|
"user#{n}#example.com"
end
factory :user do
email
first_name Faker::Name.first_name
last_name Faker::Name.last_name
password "password"
password_confirmation "password"
agreed_to_age_requirements true
username "testing123"
state "AL"
city_id 201
school_id 20935
handedness "Left"
customer_id { "#{rand(1000)}" }
after(:create) do |user, elevator|
user.subscriptions << FactoryGirl.create(:subscription, account_type_name: "#{elevator.account_type_name}")
user.sports << FactoryGirl.create(:sport)
user.roles << FactoryGirl.create(:role)
end
end
factory :athlete, class: "Athlete", parent: :user do
type "Athlete"
recruit_year "2016"
end
end
Subscriptions.rb
FactoryGirl.define do
factory :subscription do
trial_expiry 30.days.from_now
active true
after :create do |subscription, elevator|
account_type {create(:account_type, name: "#{elevator.account_type_name}", price: 0)}
end
end
end
AccountTypes.rb
FactoryGirl.define do
factory :account_type do
name "Legend"
price 15
trial_period_days 0
videos 20
contributors 15
end
end
Here is what my test looks like:
before :each do
#user = create(:user)
#sport_user = create(:user, sports: [])
#school_admin_role = create(:role, name: "School Admin")
#contributor_role = create(:role, name: "Contributor")
end
The problem is that when I create a second user, the Account Type that is associated with the first user's subscription has already been created and so the same account type already exists in my testing db. Any way to write this so that this doesn't happen?
Here's what I'm trying to get at in my comment above. If this doesn't work, let me know and I'll delete the answer.
Users.rb
FactoryGirl.define do
sequence(:email) do |n|
"user#{n}#example.com"
end
factory :user do
email
first_name Faker::Name.first_name
last_name Faker::Name.last_name
password "password"
password_confirmation "password"
agreed_to_age_requirements true
username "testing123"
state "AL"
city_id 201
school_id 20935
handedness "Left"
customer_id { "#{rand(1000)}" }
subscriptions {[create(:subscription, account_type_name: "#{account_type_name}")]}
roles {[create(:role)]}
after(:create) do |user|
user.sports << FactoryGirl.create(:sport)
end
end
factory :athlete, class: "Athlete", parent: :user do
type "Athlete"
recruit_year "2016"
end
end
Subscriptions.rb
FactoryGirl.define do
factory :subscription do
trial_expiry 30.days.from_now
active true
after(:create) do |subscription, evaluator|
account_type {create(:account_type, name: "#{evaluator.account_type_name}", price: 0)}
end
end
end
AccountTypes.rb
FactoryGirl.define do
factory :account_type do
name "Legend"
price 15
trial_period_days 0
videos 20
contributors 15
end
end
Here is what my test looks like:
before :each do
#school_admin_role = create(:role, name: "School Admin")
#contributor_role = create(:role, name: "Contributor")
#user = create(:user, account_type_name: "Free")
#sport_user = create(:user, sports: [], account_type_name: "Other Free Name")
end
I can't figure out why this code is not populating my sqlite database. I am using the faker gem with rails 3.2 and am trying to make a twitter like application. Can anyone find the problem?
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
def make_users
User.create!(name: "Example User",
email: "example#example",
password: "foobar",
password_confirmation: "foobar")
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}#example.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
end
end
I figured out the answer actually. Here is the correct code:
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
make_users
make_microposts
make_relationships
end
end
def make_users
User.create!(name: "Example User",
email: "example#railstutorial.org",
password: "foobar",
password_confirmation: "foobar")
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