Reputation: 544
My Project model has a start_date
and end_date
. I want to filter projects with a range of start_year
and end_year
.
Current implementation:
class Project < ActiveRecord::Base
...
def self.date_range(start_year, end_year)
end
end
Upvotes: 0
Views: 96
Reputation: 1568
Assuming your start_date, end_date are all DateTime objects and start_year, end_year are just the value of year e.g. 2013, 2014 etc., the query should look like this.
Project.where('EXTRACT(YEAR from start_date) <= ? AND EXTRACT(YEAR from end_date) >= ?', start_year, end_year)
Upvotes: 1
Reputation: 1491
You could do it using AREL dsl for building sql queries like so:
class Project < ActiveRecord::Base
scope :in_date_range, ->(start_year, end_year) do
where(arel_table[:start_date].gt(start_year).and(arel_table[:end_date].lt(end_year))
end
end
And then use it like
Project.in_date_range(start, end)
Would return projects in specified range
Upvotes: 0