【问题标题】:What is the best way to add seven days recursively to a date in ruby on rails 5.2.3在 ruby​​ on rails 5.2.3 中递归添加 7 天的最佳方法是什么
【发布时间】:2021-02-06 09:12:50
【问题描述】:

我目前创建多个预订端点,这需要数周作为参数“数量”。

到目前为止,我有这个:

在我的控制器操作中:

     def multiple
          @qty = params[:qty]
          @booking = Booking.new(booking_params)
          if @booking.save 
            @newbookings = @booking.createmore(@qty)
            render json: @newbookings, status: :created
          else 
            render json: @booking.errors, status: :unprocessable_entity
          end
      end

在我的模型中,我有一个创建多个的例程。

    def createmore(quantity)
        bookings = []
        quantity.to_i.times do 
            bookings.push(self)
        end 
        puts "#{@bookings}"
        newbookings = []
        firstBooking = self

        bookings.each do | booking |
            booking.start = firstBooking.start
            booking.end = firstBooking.end
            booking.name = firstBooking.name
            booking.email = firstBooking.email
            booking.contact = firstBooking.contact
            newbookings.push(booking)
        end
        newbookings.each do | booking |
            booking.save
        end
    end

问题是,如何递归地在日期上添加一周。即第二次预订增加 7 天,第三次预订增加 14 天,第四次预订增加 21 天,以此类推,直到数量为零。

我可以在 JavaScript 中立即执行此操作,但不知道从哪里开始使用 ruby​​。我非常感谢任何帮助。

【问题讨论】:

    标签: ruby-on-rails math ruby-on-rails-5


    【解决方案1】:

    您可以使用 Enumerable 模块中的 each_with_index 方法以及 Active Support 中包含的 time management extensions 的新增功能。一个简化的示例如下所示:

    bookings.each_with_index do |booking, i|
      booking.start = firstBooking.start + i.weeks
    end
    

    索引i从0开始,所以第一次预订会保持原来的开始日期(加0周)。剩下的几周将比原来的晚i 周开始。

    编辑

    正如 Scott 所指出的,每当其中一个元素被更新时,它们都会被更新。这里的关键是没有可以独立更新的带有n 对象的数组,有一个带有n 对同一对象的引用的数组,因此对其中一个对象所做的更改适用于所有对象。

    可能你每次都想pusha copy of the original object而不是推送原始元素:

    quantity.to_i.times do 
      bookings.push(self.dup)
    end
    

    通过这样做,将有效地得到原始对象的n 副本,您将能够分别更新它们中的每一个。

    【讨论】:

    • 谢谢,我试过了,但它似乎将最后一个索引添加到所有日期,而不是每个索引
    • 我也拿了 .在 do 之前退出,否则它会吐出语法错误
    • 我已经更新了答案,删除了错字并添加了解决您提到的问题的方法
    猜你喜欢
    • 2012-03-21
    • 1970-01-01
    • 2010-12-08
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多