当我运行db:populate
时,它会出现以下错误:
Validation failed: Email has already been taken, Nyaaid has already been taken
电子邮件应该是唯一的,ID应该是唯一的!这是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 }
这是Faker代码,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
答案 0 :(得分:2)
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: "")
在创建第一个对象之前添加Awardunit.destroy_all
。