0

I just started learning some database basics. I am using Ruby and the datamapper gem

I have two simple objects:

class Quote
  include DataMapper::Resource
  property :id, Serial
  property :saying, String, :required => true
  property :score, Integer, :default => 5
  belongs_to :user
end

and

class User
  include DataMapper::Resource
  property :id, Serial
  has n, :quotes
end

No I would like to get the total score of a user. The total score is the sum of the scores of all associated quotes of a user.

I tried something like

@totalscore = @user.quotes.inject(0) {|count, q| count + q.score}

but I guess this can't be the way I am supposed to use a database, right?

Any help is appreciated!

Best,

Tobi

tobias.henn
  • 225
  • 2
  • 13

1 Answers1

2

I am not running the code, but by looking at the docs, I think something like this should work:

@totalscore = @user.quotes.sum :score
Jiří Pospíšil
  • 14,296
  • 2
  • 41
  • 52