in my application.record.rb
def total_price
Ticket.sum(:price)
end
in my ticket index
<% @tickets.each do |t| %>
t.total_price
<% end %>
它可以工作,但可以计算出机票总价。
我想要的是我可以将每日总价,每周总价和每月总价分开。
该怎么做? 请帮忙,谢谢..
答案 0 :(得分:1)
每日总价
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 %>
答案 1 :(得分:0)
您可以使用以下模型作用域-
class Ticket < ApplicationRecord
scope :daily_total_price, ->(date_time = Time.now) { where('created_at BETWEEN ? AND ?',date_time.beginning_of_day, date_time.end_of_day).sum(:subtotal) }
scope :weekly_total_price, ->(date_time = Time.now) { where('created_at BETWEEN ? AND ?',date_time.beginning_of_week, date_time.end_of_week).sum(:subtotal) }
scope :monthly_total_price, ->(date_time = Time.now) { where('created_at BETWEEN ? AND ?',date_time.at_beginning_of_month, date_time.end_of_month).sum(:subtotal) }
scope :last_7d_total_price, ->(date_time = Time.now) { where('created_at >= ?', (date_time - 7.days).beginning_of_day).sum(:subtotal) }
scope :last_30d_total_price, ->(date_time = Time.now) { where('created_at >= ?', (date_time - 30.days).beginning_of_day).sum(:subtotal) }
end
范围的使用
Ticket.daily_total_price # For daily scope
Ticket.weekly_total_price # For Weekly scope
Ticket.monthly_total_price # For monthly scope
Ticket.last_7d_total_price # For last 7 days scope
Ticket.last_30d_total_price # For 30 days scope
您还可以传递一个特定的日期作为参数
# With time zone
date_time_with_zone = Time.zone.parse("2018-09-30")
Ticket.daily_total_price(date_time_with_zone)
# Without time zone
date_time = Time.parse("2018-09-30")
Ticket.daily_total_price(date_time)
我希望它能满足您的要求。