I have in the database two date columns - from_date
and to_date
.
Example:
from_date
: 2012-09-10
you can use like this:
Data = Model.where("date(now()) between from_date and to_date")
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.