ruby-on-rails - rails : Find entries by date

标签 ruby-on-rails ruby ruby-on-rails-4

我正在运行 Ruby 2 和 Rails 4。

我正在创建一个应用程序,您可以在其中跟踪特定日期每顿饭的卡路里和大量营养素,但我希望能够回顾前几天。

我有一个表格,显示今天通过模型中的范围在索引页上输入了哪些餐食。我如何在 Rails 中实现回顾其他日子的能力?

我应该添加日期模型还是给每顿饭一个日期时间?有这样的 gem 吗?

膳食模型

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

膳食 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

谢谢!

最佳答案

首先,您可以简化您的 today 范围,因为实际上无法在今天结束之前创建某些内容(使用标准 Rails 方法,除非您手动更新created_at 日期)。

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

对于前几天,您可以使用以下范围来抓取它们并按天进行分组

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

如果您要查找特定日期,可以使用以下内容:

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

作为被调用方法的示例:current_user.meals.for_date(6.days.ago)

关于ruby-on-rails - rails : Find entries by date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19519155/

相关文章:

ruby-on-rails - 切换到 Ruby 2.3.0(从 2.0.0 开始)会在 Active Record 验证上产生问题

javascript - Webpacker 重构后 react 组件不呈现

ruby - 多维各

ruby - 无法写入守护进程中的日志

ruby-on-rails - rails : accessing field value from model method

ruby-on-rails - Controller 无法识别已安装的 Gem

ruby-on-rails - 无法运行 rake Assets :precompile in rails

javascript - 在 Rails 5.1.4 中包含 JS 脚本

ruby-on-rails - Activerecord has_many :through through multiple models

ruby-on-rails - 带有 splat 参数的 Rake 任务