从2D数组中获取值

时间:2016-08-30 14:06:46

标签: mysql ruby-on-rails arrays ruby

我已使用此查询检索某个特定用户的已批准树叶的日期 -

LeaveRequest.where(user_id: 6).where(status: 1).pluck(:from_date, :to_date)

我将此数组作为结果 -

[[Mon, 12 Sep 2016, Fri, 16 Sep 2016], [Tue, 06 Sep 2016, Tue, 06 Sep 2016], [Thu, 01 Sep 2016, Fri, 02 Sep 2016], [Tue, 30 Aug 2016, Wed, 31 Aug 2016]] 

我想要的是获取所有日期以及2016年9月12日至2016年9月16日(13日14日和15日)之间的日期。

1 个答案:

答案 0 :(得分:2)

我假设你的意思是这样的

require 'date'
#This is to simulate your current Array
current_array = 5.times.map {|n [Date.new(2016,n+1,1).<<(1),Date.new(2016,n+1,1)]}
#map the 2 dates to a Range
new_array = current_array.map{|start_date,end_date| (start_date..end_date)} 
new_array.first.class
#=> Range

在范围内拨打to_a会将其分为start_dateend_date

之间的所有日期

使用rails可以执行类似

的操作
class LeaveRequest
  def self.user_requested_ranges(user_id, status_id)
    scoped.
      where(user_id: user_id, status: status_id).
      pluck(:from_date, :to_date).
      map do |from_date, to_date|
        #optionally to output the full Array in each Range you could use 
        #(from_date..to_date).to_a  
        (from_date..to_date)
      end
  end
end

然后打电话给

LeaveRequest.user_requested_ranges(6,1)
相关问题