如何在Rake脚本中增加值?

时间:2011-01-17 23:46:43

标签: ruby-on-rails rake rails-migrations

如何将此:project_pages_id => 1值更改为自动增量?

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

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

你需要迭代一个像:

这样的数组
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)}

我确信还有其他方法,但这很快,很脏,而且只是一个测试。

答案 2 :(得分:1)

project_pages_id是否是外键?如果是这样,为什么你会自动递增它以使它具有nil关联?

看起来你正在尝试创建种子数据。一个好方法是使用Factory Girl:

https://github.com/thoughtbot/factory_girl

除此之外,它还有“序列”的概念,它解决了你原来的问题:

# 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"