1

How do I make the clients/index show only clients with negative balance?

I have Client.rb:

has_many :incomes
has_many :expences

  def all_incomes
      incomes.map(&:amount).sum
  end
  def all_expences
      expences.map(&:amount).sum
  end
  def balance
    all_incomes - all_expences
  end
end

ClientsController.rb:

  def index
    @client = Client.where(:balance < 0)
  end

Taking into consideration, that "balance" is not saved as a column of the table in the database...

Yshmarov
  • 3,450
  • 1
  • 22
  • 41
  • Sure, it would have worked if `balance` was saved in the database, but it is not. It is a field, calculated in the model... – Yshmarov May 18 '17 at 22:02

2 Answers2

3

You can use Enumerable#select to filter in Ruby:

class Client 
  def all_incomes
    incomes.map(&:amount).sum
  end
  def all_expences
    expences.map(&:amount).sum
  end
  def balance
    all_incomes - all_expences
  end

  def self.postive_balance
    self.all.select {|c| c.balance < 0 }
  end
end

However its going to be very inefficient given a large enough amount of clients. You should instead select aggregates of incomes.amount and expenses.amount and do the calculation on the database level.

Community
  • 1
  • 1
max
  • 96,212
  • 14
  • 104
  • 165
1
  def index
    @client = Client.joins(:incomes,:expenses).having("SUM(incomes.amount) - SUM(expenses.amount) < 0")
  end

Join with both models and apply condition while querying as above. This will be much faster.

rohan
  • 1,606
  • 12
  • 21