I have an ActiveRecord model that has a date attribute. Is it possible to utilize that date attribute to find by Year, Day and Month:
Model.find_by_year(201
In your Model:
scope :by_year, lambda { |year| where('extract(year from created_at) = ?', year) }
In your Controller:
@courses = Course.by_year(params[:year])
Another short scope as below:
class Leave
scope :by_year, -> (year) {
where(date:
Date.new(year).beginning_of_year..Date.new(year).end_of_year)
}
end
Call the scope:
Leave.by_year(2020)
If you're looking for just the date, simply do:
Model.where(date: Date.today.beginning_of_day..Date.today.end_of_day)
app/models/your_model.rb
scope :created_in, ->( year ) { where( "YEAR( created_at ) = ?", year ) }
Usage
Model.created_in( 1984 )
Try this:
Model.where("MONTH(date_column) = ? and DAY(date_column) = ?", DateTime.now.month, DateTime.now.day)
I usually use:
Model.where('extract(month from birthday_column) = ? and extract(day from birthday_column) = ?', Time.now.month, Time.now.day)