Yshmarov
Yshmarov

Reputation: 3729

rails controller filter on method

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...

Upvotes: 1

Views: 874

Answers (2)

rohan
rohan

Reputation: 1656

  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.

Upvotes: 1

max
max

Reputation: 101811

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.

Upvotes: 3

Related Questions