Reputation: 43
I'm trying to seed my database with project with unique project name, however my seeder does not work as I intended.
Seed.rb
users = User.order(:created_at).take(6)
50.times do |n|
name = "project-#{n+1}"
category = "category-#{n+1}"
users.each { |user| user.projects.create!(name: name, category: category) }
end
If I remove validates :name, presence: true, uniqueness: true
it will create 50 projects for each user from 1 to 50, but then for the next user would do the same (count resets) and will create projects with titles from 1 to 50 which interferes with the validates rule.
Any ideas?
Upvotes: 0
Views: 67
Reputation: 5214
You can get last project_id
and initial counter with it. Too user.id
as additional scope.
last_id = Project.last.try(:id) || 1
50.times do |n|
name = "project-#{last_id+n}"
category = "category-#{last_id+n}"
users.each do |user|
user.projects.create!(name: ("#{name}-#{user.id}"), category: ("#{category}-#{user.id}"))
end
end
Too you can add rand
, Time.now.to_f.to_s
, SecureRandom.hex(5)
Upvotes: 1