0

I have used this query to retrieve the dates for one particular user's approved leaves -

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

and I'm getting this array as result -

[[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]] 

what I want is to fetch all the dates as well as the dates between 12 Sep 2016 and 16 Sep, 2016 (13th 14th and 15th).

2
  • Are the array results strings? Because otherwise the array doesent make too much sense? Aug 30, 2016 at 14:19
  • @MuntasirAlam, well the dates are of "date" datatype.
    – s_a
    Aug 30, 2016 at 14:33

1 Answer 1

2

I am assuming you mean something like this

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

Calling to_a on the Range will blow it out into all the dates between start_date and end_date

With a rails you could do something like

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

Then call as

LeaveRequest.user_requested_ranges(6,1)
1
  • @sharma_a my answer still applies. pluck will return an Array and you can convert that Array to an Array of ranges. I will add a rails way for you just to make this clearer. Aug 30, 2016 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.