Question

How can I change this :project_pages_id => 1 value to auto increment?

  user.projects.create!(:title => Faker::Lorem.sentence(1), :project_pages_id => 1)
Was it helpful?

Solution

10.times do |n|
  user.projects.create!(:title => Faker::Lorem.sentence(1), :project_pages_id => n
end

OTHER TIPS

You'd need to iterate over an array like:

a = (1..10).to_a #or however many ID's you want.
a.each do {|d|   user.projects.create!(:title => Faker::Lorem.sentence(1), :project_pages_id => d)}

I'm sure there is other ways, but this is quick and dirty, and it's only a test.

Is that project_pages_id intended to be a foreign key? If so, why would you auto-increment it such that it will have a nil association?

It looks like you're trying to create seed data. A good way to do that is to use Factory Girl:

https://github.com/thoughtbot/factory_girl

Among other things, it has the concept of "sequences", which solves your original question:

# Defines a new sequence
Factory.sequence :email do |n|
  "person#{n}@example.com"
end

Factory.next :email
# => "person1@example.com"

Factory.next :email
# => "person2@example.com"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top