Tomer Lichtash
Tomer Lichtash

Reputation: 9262

How to increment a value in a Rake script?

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)

Upvotes: 1

Views: 265

Answers (3)

Dan Croak
Dan Croak

Reputation: 1669

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
# => "[email protected]"

Factory.next :email
# => "[email protected]"

Upvotes: 1

gunn
gunn

Reputation: 9165

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

Upvotes: 3

pjammer
pjammer

Reputation: 9577

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.

Upvotes: 1

Related Questions