Rails ActiveRecord - how to fetch records between two dates

后端 未结 8 1243
执念已碎
执念已碎 2020-12-29 23:16

I have in the database two date columns - from_date and to_date.

Example:

  • from_date: 2012-09-10
相关标签:
8条回答
  • you can use like this:

    Data = Model.where("date(now()) between from_date and to_date")
    
    0 讨论(0)
  • 2020-12-29 23:57

    Ok, after a long search in google looking for a "rails way" to do a BETWEEN with two date fields and a variable, the most approximate solution I found is creating your own scope to do that.

    in your ApplicationRecord write:

    class ApplicationRecord < ActiveRecord::Base
    
      scope :between_fields, -> (value, initial_date, final_date) { 
        where "('#{value}' BETWEEN #{initial_date} AND #{final_date})"
       }
    
    end
    

    So now, wherever you need to do a between you can do:

    @clients = Client.between_fields(params[:date], :start_date, :final_date)
    # SELECT * FROM clients WHERE ('2017-02-16 00:00:00' BETWEEN start_date AND final_date)
    

    You can combine it with others "where" to do your query as specific as you need.

    0 讨论(0)
提交回复
热议问题