对于我的Rails应用程序,我正在尝试构建一个rake任务,为每个invoices
填充10 user
个数据库:
def make_invoices
User.all.each do |user|
10.times do
date = Date.today
i = user.invoices.create!(:number => user.next_invoice_number,
:date => date += 1.year)
i.save
end
end
end
如何将date
增加一年?
答案 0 :(得分:5)
将您的循环更改为:
10.times do |t|
puts t + 1 # will puts 1,2,3,4,5,6,7,8,9,10
end
现在你可以设定你的年份。
答案 1 :(得分:1)
这是使用Date#next_year
:
require 'date'
d = Date.today
d # => #<Date: 2013-09-21 ((2456557j,0s,0n),+0s,2299161j)>
d.next_year # => #<Date: 2014-09-21 ((2456922j,0s,0n),+0s,2299161j)>
答案 2 :(得分:1)
def make_invoices
User.all.each do |user|
date = Date.today
10.times do
user.invoices.create!(:number => user.next_invoice_number,
:date => (date += 1.year))
end
end
end
因为date = Date.today
循环中有10.times
,所以它会在每个循环中重置。只需将date = Date.today
移到循环之外。
答案 3 :(得分:1)
您可以利用Date#next_year
,其中的参数表示您想要推进多少年:
def make_invoices
User.all.each do |user|
10.times.with_object(Date.today) do |i, date|
user.invoices.create!(
number: user.next_invoice_number,
date: date.next_year(i)
)
end
end
end
Numeric#times
将索引传递给阻止。
Enumerator#with_object
允许将其他参数传递给block,我们在这里使用它来避免在块外设置局部变量(因为我们不需要在外面)。