Datamapper: count favs - ruby

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?

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

Related

Tracking wins & losses with PSQL/DataMapper

I have a User class which allows people to register and play a game; I also have a Game class, which contains the logic of said game (RPS).
When people register, their information is held in a psql database. The informations is obtained using params. It looks like this:
Class User
attr_reader :weapon
include DataMapper::Resource
property :id, Serial
property :name, String, required: true
property :email, String, required: true, unique: true
property :password_digest, Text
attr_reader :password
attr_accessor :password_confirmation
validates_confirmation_of :password
validates_format_of :email, as: :email_address
has n, :games
The corresponding Game class, contains this DB logic:
class Game
include DataMapper::Resource
property :id, Serial
property :win, ?
property :lose, ?
belongs_to :user
My issue is that I really don't know how to keep a record of how many games the user has won/lost. Do I need (or should I have separate classes for wins and losses? What key type should I use (serial/int)? All I want is for 'win' or 'lose' to increment by one each time the player...well, wins or loses.
All help/knowledge shared is greatly appreciated.
Thanks.
One way to do it could be to add two integer columsn "wins" and "losses" to User, and make helper methods to increment:
property :wins, Integer, default: 0
property :losses, Integer, default: 0
# usage: user.increment(:wins) or user.increment(:losses)
def increment(type)
update({ type => (send(:type) + 1) })
end

Datamapper: How to count total score from has_many objects

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
I am not running the code, but by looking at the docs, I think something like this should work:
#totalscore = #user.quotes.sum :score

How can I have two many-to-many relationships to the same model in DataMapper?

edit: Updated question to show my use of :child_key => [:comparison_id] as suggested in the comment.
I have two models that look like this:
class Comparison
include DataMapper::Resource
property :id, Serial
end
class Msrun
include DataMapper::Resource
property :id, Serial
property :name, String
end
Comparison come from comparing two sets of Msruns. I thought I would represent this through two many-to-many relationships from Comparison to Msrun, but I am beating my head against the wall as to how to do this in DataMapper. I know that many-to-many relationships are available by adding something like this:
has n, :whatevers, :through => Resource
However, this will only make one many-to-many relationship between the two models. I have also tried creating two join models and manually specifying the relationships, and manually specifying the child key for each relationship like so:
# Join model for the comparison-msrun many-to-many relationship.
class First
include DataMapper::Resource
belongs_to :msrun, :key => true
belongs_to :comparison, :key => true
end
# Join model for the comparison-msrun many-to-many relationship.
class Second
include DataMapper::Resource
belongs_to :msrun, :key => true
belongs_to :comparison, :key => true
end
class Comparison
include DataMapper::Resource
property :id, Serial
has n, :firsts
has n, :msrun_firsts, 'Msrun', :through => :firsts, :child_key => [:msrun_id]
has n, :seconds
has n, :msruns_seconds, 'Msrun', :through => :seconds, :child_key => [:msrun_id]
end
class Msrun
include DataMapper::Resource
property :id, Serial
property :name, String
has n, :firsts
has n, :comparison_firsts, 'Comparison', :through => :firsts, :child_key => [:comparison_id]
has n, :seconds
has n, :comparison_seconds, 'Comparison', :through => :seconds, :child_key => [:comparison_id]
end
Running automigrate results in the following error:
rake aborted!
No relationships named msrun_firsts or msrun_first in First
What am I doing wrong here? How can I make this work?
What you're observing, is the fact that relationships are stored in a set like object under the hood, more specifically, a set that uses the relationship's name as discriminator. So what happens in your case, is that the latter definition overwrites the former, as sets don't allow duplicate entries (and in our case, replace the older entry with the newer, for the set's purposes, identical one).
There are practical reasons for this. It makes no sense to declare two supposedly different relationships on one model, but name them the same. How would you distinguish them when trying to access them? This manifests itself in DM's implementation, where a method named by the relationship name gets defined on the Resource. So what DM ends up doing in your case of trying to add a duplicate to the set, is that it will just use the latter options to generate the implementation of that method. Even if it were to accept duplicate relationship names, the latter relationship would lead to an overwritten/redefined version of the same method, thus leaving you with the same net effect.
As a consequence, you would need to define differently named relationships on your models. When you think about it, it really makes sense. To help DM with inferring the model to use, you can pass the model name (or the constant itself) as the 3rd parameter to the has method, or as the 2nd parameter for belongs_to
class Comparison
include DataMapper::Resource
property :id, Serial
has n, :firsts
has n, :first_msruns, 'Msrun', :through => :firsts
has n, :seconds
has n, :second_msruns, 'Msrun', :through => :seconds
end
class Msrun
include DataMapper::Resource
property :id, Serial
property :name, String
has n, :firsts
has n, :first_comparisons, 'Comparison', :through => :firsts
has n, :seconds
has n, :second_comparisons, 'Comparison', :through => :seconds
end
Hope that helps!
As per the DataMapper docs
I believe you can do:
class Msrun
include DataMapper::Resource
property :id, Serial
property :name, String
has n, :firsts #This line could probably be omitted
has n, :first_comparisons, 'Comparison', :through => :firsts
has n, :seconds #This line could probably be omitted
has n, :second_comparisons, 'Comparison', :through => :seconds
end

Correct way to make a DataMapper association

I want to have a table of users. These users shall have n contacts and n messages..
My code is:
...
class User
include DataMapper::Resource
property :id, Serial, :key => true
property :nickname, String
has n, :contacts
has n, :messages
end
class Contact
include DataMapper::Resource
belongs_to :user
property :id, Serial, :key => true
property :authgiven, String
has 1, :user
end
class Message
include DataMapper::Resource
belongs_to :user
property :id, Serial, :key => true
property :data, String
end
#apply models (validation etc.)
DataMapper.finalize
...
There are no errors initializing DataMapper, but when I try to create a new User or whatever, save always returns false... Can someone please point out what is wrong?
I'm quite new to DataMapper, it always worked for me with simple tables without relationships, so I believe it has to do with the way I declared the 1:n relationship...
Hey you should remove that has 1, :user line from Contact model and you should be good.

Datamapper's hooks won't work

Can't understand why hooks don't work. I have the following model:
class DirItem
include DataMapper::Resource
# property <name>, <type>
property :id, Serial
property :dir_cat_id, Integer, :required => true
property :title, String, :required => true
property :price, Integer, :default => 0
belongs_to :dir_cat
has n, :dir_photos
has n, :dir_field_values
before :destroy do
logger.debug "==============DESTROYING ITEM ##{id}, TITLE
#{title}"
dir_field_values.destroy
dir_photos.destroy
end
end
When I call destroy method either from my app or irb, it returns false. The errors hash is empty, the log message doesn't print and the record won't delete.
This hook works for me (ruby 1.9.2 / DM 1.0.2):
require 'rubygems'
require 'dm-core'
require 'dm-migrations'
# setup the logger
DataMapper::Logger.new($stdout, :debug)
# connect to the DB
DataMapper.setup(:default, 'sqlite3::memory:')
class DirItem
include DataMapper::Resource
# property <name>, <type>
property :id, Serial
property :dir_cat_id, Integer, :required => true
property :title, String, :required => true
property :price, Integer, :default => 0
has n, :dir_photos
before :destroy do
dir_photos.destroy
end
end
class DirPhoto
include DataMapper::Resource
property :id, Serial
belongs_to :dir_item
end
DataMapper.finalize.auto_migrate!
#i = DirItem.create(:title => 'Title', :dir_cat_id => 1)
#i.dir_photos.create
#i.dir_photos.create
#i.dir_photos.create
#i.destroy
The DM logger reveals that each of the dir_photos are destroyed before the dir_item is. Instead of using hooks, you might want to look into using dm-constraints though. With something like:
has n, :dir_photos, :constraint => :destroy
you can be sure that all the dir_photos will be destroyed when the dir_item is destroyed, and this will also be enforced by database level foreign key constraints.

Resources