Finally I implemented ut as follows:
class Client < ActiveRecord::Base
...
scope :accounts_sum, includes(:accounts =>
:operations).group(''clients.id'').order(''clients.lastname'')
def accounts_balance
accounts.map(&:balance).inject(:+) unless accounts.empty?
end
end
And here are the changes in the OperationsController:
def index
@operations = Client.accounts_sum.paginate(page: params[:page])
@total = @operations.map(&:accounts_balance).inject(:+) unless
@operations.empty? #to be able to display the total of all the existing
accounts.
end
HTH
On Tuesday, November 20, 2012 1:01:06 PM UTC+1, Javix
wrote:>
> I have the following models:
>
> class Client < ActiveRecord::Base
> has_many :accounts, dependent: :destroy
> end
>
> class Account < ActiveRecord::Base
> belongs_to :client
> has_many :operations, dependent: :destroy
> end
>
> class Operation < ActiveRecord::Base
> belongs_to :account
> end
>
> I manage to extract clients and all their operations grouped by client as
> follows:
>
> scope :operations_by_client, joins(:client,
> :operations).select(''clients.firstname, clients.lastname,
> sum(operations.total) as total'').group(''clients.id,
clients.firstname,
> clients.lastname'').order(''clients.lastname'')
>
> Now how to tune/change it in case if I don''t need to calculate SUM
of the
> operations but to use a special method that would calculate the sum of all
> the operations for the specified client? I mean that I should exclude
> certain total values from the calculation depending on the operation type.
>
> Thanks and regards
>
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To view this discussion on the web visit
https://groups.google.com/d/msg/rubyonrails-talk/-/LIE0Wg7A5xoJ.
For more options, visit https://groups.google.com/groups/opt_out.