如何增加 Rake 脚本中的值?

发布于 2024-10-12 15:23:30 字数 174 浏览 5 评论 0原文

如何更改此 :project_pages_id => 1 值自动递增?

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

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

菊凝晚露 2024-10-19 15:23:30
10.times do |n|
  user.projects.create!(:title => Faker::Lorem.sentence(1), :project_pages_id => n
end
10.times do |n|
  user.projects.create!(:title => Faker::Lorem.sentence(1), :project_pages_id => n
end
余罪 2024-10-19 15:23:30

您需要迭代一个数组,例如:

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)}

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

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.

怎会甘心 2024-10-19 15:23:30

该project_pages_id是否打算作为外键?如果是这样,为什么要自动递增它以使其具有零关联?

您似乎正在尝试创建种子数据。一个好方法是使用 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
# => "[email protected]"

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

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]"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文