ARTLoe
ARTLoe

Reputation: 1799

method containing calculation - Rails 4

i just want to calculate the total sum of all active events that users have paid to attend. If you could advise me i could be grateful as i am very unsure. Many thanks

event.rb
has_many :payments

payment
belongs_to :event

in the event.rb i tried the below method but no success

def self.active_events
    active_events = live_events.open_events
    active_events.all.each do |event|
      event.price * event.payments.count
    end
  end

Upvotes: 0

Views: 34

Answers (2)

dnsh
dnsh

Reputation: 3633

You can do this simply in following way,

total = 0
Event.live_events.open_events.find_each { |e| total += e.price * e.payments.count }

In Event.rb place it in a method with meaningful name. This will work for you.

def self.total_price_for_active_events
  total = 0
  Event.live_events.open_events.find_each { |e| total += e.price * e.payments.count }
  total
end

Most optimized way

def self.total_price_for_active_events
  Event.live_events.open_events.joins(:payments).sum("events.price")
end

Upvotes: 3

Hamms
Hamms

Reputation: 5107

You're off too a good start! Unfortunately, what you have there is only the beginning; you're generating an array that contains the total sum for each event. All that remains is to add them together:

  def self.active_events
    active_events = live_events.open_events
    costs = active_events.all.each do |event|
      event.price * event.payments.count
    end
    costs.reduce(0) do |sum,x|
      sum + x
    end
  end

You could also get real fancy and simply use:

costs.reduce(0, :+)

Upvotes: 1

Related Questions