Rails - 如何计算 Rails 上的每日、每周、每月总价 [英] Rails - How to calculate daily, weekly, mothly total price on rails

查看:33
本文介绍了Rails - 如何计算 Rails 上的每日、每周、每月总价的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有售票模型,参数为 :quantity, :price

I have Ticket sold model with params :quantity, :price

in my application.record.rb
def total_price
 Ticket.sum(:price)
end

in my ticket index
<% @tickets.each do |t| %>
  t.total_price
<% end %>

它有效,但它计算了所有门票总价.

It Worked but it calculated all of ticket total price.

我想要的是我可以将每日总价、每周总价和每月总价分开.

What i want is i can separating between daily total price, weekly total price and monthly total price.

怎么做?请帮忙,谢谢..

How to do that? Please help and thank you..

推荐答案

每日总价

def daily_total_price
 Ticket.where("created_at >= ? AND created_at < ?", Time.now.beginning_of_day, Time.now.end_of_day).sum(:subtotal)
end

每周总价

def weekly_total_price
 Ticket.where("created_at >= ?", Time.now.beginning_of_week).sum(:subtotal)
end

每月总价

def monthly_total_price
 Ticket.where("created_at >= ?", Time.now.beginning_of_month).sum(:subtotal)
end

过去 7 天总计

def last_7_day_total_price
  Ticket.where("created_at >= ? ", (Date.today - 7.days).beginning_of_day).sum(:subtotal)
end

过去 30 天总计

def last_30_day_total_price
  Ticket.where("created_at >= ? ", (Date.today - 30.days).beginning_of_day).sum(:subtotal)
end

在视图中

<% @tickets.each do |t| %>
  Daily total price: - <%=t.daily_total_price%>
  Weekly total price: - <%=t.weekly_total_price%>
  #.....so on..
<% end %>

这篇关于Rails - 如何计算 Rails 上的每日、每周、每月总价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆