Luke Macauley
Luke Macauley

Reputation: 50

Rails: Find entries by date

I'm running Ruby 2 and Rails 4.

I am creating an app where you can track the calories and macronutrients of each meal entered on a particular day, but I would like the ability to look back at previous days.

I have a table showing what meals have been entered today on my index page through a scope in my model. How would I implement the ability to look back at other days in Rails?

Should I add in a date model or give each meal a datetime? Is there a gem for this sort of thing?

Meals Model

class Meal < ActiveRecord::Base

  scope :today, lambda { 
    where("created_at > ?", Time.now.beginning_of_day)
    .where("created_at < ?", Time.now.end_of_day) 
  }

  scope :previous, lambda {
    where("created_at < ?", Time.now.beginning_of_day) 
  }

  validates :name, presence: true
  validates :calories, presence: true, numericality: { only
  validates :protein, numericality: { only_integer: true }
  validates :carbohydrates, numericality: { only_integer: t
  validates :fats, numericality: { only_integer: true }

  belongs_to :user

end

Meals Controller

  def index
    if user_signed_in?
      @todays_meals = current_user.meals.today
      unless current_user.bmr.blank? || current_user.weight.blank? || current_user.protein_intake.blank? || current_user.fat_percentage.blank?
        @remaining_calories = (current_user.bmr) - @todays_meals.sum(:calories)
        @remaining_protein = current_user.protein_intake - @todays_meals.sum(:protein)
        @remaining_fats = (current_user.bmr * current_user.fat_percentage / 900).to_i - @todays_meals.sum(:fats)
        @remaining_carbs = carbs_calculator
        @fat_grams = current_user.fat_percentage * current_user.bmr / 900
        @carb_grams = (carbs_calculator + @todays_meals.sum(:carbohydrates))
      end
    else
      @no_header = true
    end
  end

Thanks!

Upvotes: 2

Views: 1189

Answers (1)

Jonathan Bender
Jonathan Bender

Reputation: 1909

First, you could simplify your today scope as there's really no way to have something created earlier than the end of today (using standard Rails methods, unless you're manually updating the created_at date).

scope :today, -> { 
  where("created_at > ?", Time.now.beginning_of_day)
}

As for previous days, you can use the following scope to grab them and group them by the day

scope :in_the_past_x_days, -> (x) {
  where('meals.created_at > ?', x.days.ago)
  .group("DATE(meals.created_at)")
}

If you're looking for a particular date, you can use the following:

scope :for_date, -> (date) { 
  where("created_at > ?", date.beginning_of_day)
  .where("created_at < ?", date.end_of_day) 
}

As an example of the method being called: current_user.meals.for_date(6.days.ago)

Upvotes: 4

Related Questions