Question

I am working on a Sinatra image app. I have defined Datamapper models for my users, the uploaded images, and "Favs". Each user can give a maximum of one "Fav" to each image.

class User
  include DataMapper::Resource
  property :id, Serial
  property :privilege_lvl, Integer, :default  => 0 
  property :name, String, :unique => true
  property :password_hash, BCryptHash
  has n, :images
  has n, :comments
  has n, :favs
end

class Image
  include DataMapper::Resource
  property :id, Serial
  mount_uploader :file, ImageUploader
  belongs_to :user
  property :posted_at, DateTime
  has n, :comments
  has n, :favs
end

class Fav
  include DataMapper::Resource
  property :id, Serial
  belongs_to :image
  belongs_to :user
end

Is there a way to count the total number of Favs a user has received without iterating over all the images of the user and summing up the Favs of each image?

Was it helpful?

Solution

Sounds like you need a counter cache:

This could be as simple as adding a :favs_cache to users and incrementing it whenever favs are added.

You might also want to check out this gem: dm-counter-cache

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top