LLong
LLong

Reputation: 157

Get sum of database column

I have a database table 'posts' with 3 columns: Title, content and amount. amount has a decimal data type and I'm trying to get the sum for amount for all posts.

I'd like to display this sum on the index route subtracted from the instance variable @balance.

This is the action in my controller

def index
    @posts = Post.all
    @balance = 300
    @spendingtotal = @balance - @posts.amount
end

However this is giving me an error: undefined method `amount' for #

Upvotes: 0

Views: 1948

Answers (2)

junil
junil

Reputation: 768

@posts is an array.That why the error occurs.You can use

@spendingtotal = @balance - Post.sum(:amount)

as mentioned by @falsetru

Upvotes: 3

falsetru
falsetru

Reputation: 369074

Using Enumerable#inject:

@spendingtotal = @balance - @posts.amount.inject(0) { |sum, post|
  sum + post.amount
}

Using ActiveRecord::Calculations#sum method is more preferable:

@spendingtotal = @balance - Post.sum('amount')

Upvotes: 4

Related Questions