For my Rails application I am trying to build a rake task that will populate the database with 10 invoices for each 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

How can I increment the date by one year?

有帮助吗?

解决方案

Change your loop to:

10.times do |t|
   puts t + 1 # will puts 1,2,3,4,5,6,7,8,9,10
end

And now you can set your year.

其他提示

Here it is using 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)>
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

Because you have date = Date.today in the 10.times loop, it will be reseted in each loop. Just move date = Date.today outside the loop.

You can take advantage of Date#next_year, which takes a parameter meaning how many years you want to advance :

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 pass an index to block.

Enumerator#with_object allow to pass additional parameters to block, which we here use to avoid setting a local variable outside the block (since we don't need it outside).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top