Garbela
Garbela

Reputation: 73

Rails - How to calculate daily, weekly, mothly total price on rails

enter image description hereI 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..

Upvotes: 0

Views: 977

Answers (2)

Sahidur Rahman Suman
Sahidur Rahman Suman

Reputation: 638

You can use the following model scopes -

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

Usage of Scopes

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 

Also you can pass a specific date as argument

# 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)

I hope it should work for your requirement.

Upvotes: 0

Anand
Anand

Reputation: 6531

For daily total price

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

For weekly total price

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

For monthly total price

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

Last 7 days total

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

Last 30 days total

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

In view

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

Upvotes: 2

Related Questions