我正在运行 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/