How to make a Many-To-One relationship in DataMapper - ruby

I'm trying to create an association between two models:
class Person
include DataMapper::Resource
property :id, Serial
property :name, String
end
class Country
include DataMapper::Resource
property :id, Serial
property :name, String
end
I just need a simple relationship on Person (a country_id).
My first idea was to put a has 1 property on Person:
class Person
include DataMapper::Resource
property :id, Serial
property :name, String
has 1, :country
end
Instead of a country_id on Person table, Datamapper created a person_id on Country.
To get what I need, I had to make it inverse:
class Country
include DataMapper::Resource
property :id, Serial
property :name, String
has 1, :person
end
This way I got my country_id field on Person table, but it really doesn't make any sense for me.
Am I misunderstanding something or is there another way to make this association?

Whenever Model A "has" Model B (either one or many), you add the foreign key to Model B.
The flipside of this is "belongs to" - that's what you put on the Model with the foreign key.
I guess in DataMapper you don't have to add foreign key columns explicitly, but you could still do it if you want.
# Person
property :country_id, Integer
Since the foreign key in on Person, you'd use "belongs to". It seems like the same thing as "has one", but it's not. You generally only need "has one" in special cases like one-to-one relationships.
# Person
belongs_to :country
# Country
has n, :people
# you could use has 1, :person if for some reason every country
# only had 1 person in it

Related

DataMapper: one-to-many relationship with custom name?

I'm trying to build a small model consisting of two entities. For the purposes of this question, call them A and B. A has a one-to-many relationship to several Bs; this means that each B belongs_to an A.
In this particular case, I'd like to call the relationship from B back to A something other than a. I think I got close with the following:
class A
include DataMapper::Resource
property :id, Serial
has n, :bs
end
class B
include DataMapper::Resource
property :id, Serial
belongs_to :owner, 'A'
end
The important bit here is the belongs_to :owner, 'A' line in B. With this, I can successfully:
Create and save an instance of A
Query that A for its bs and get an empty array back
Create an instance of B, assigning its owner to be the A I made earlier
However, when I go to save that instance of B, I run into trouble – calling save returns false. If I print the B, I see that it has two attributes: one called owner_id and another called a_id.
What else do I need to do with this model to rename the relationship from B back to A? Is such a rename even possible?
Figured it out. The owning entity (A) needs to explicitly specify the child keys that it wants created for the relationship:
class A
include DataMapper::Resource
property :id, Serial
has n, :bs, :child_key => [ 'owner_id' ]
end
class B
include DataMapper::Resource
property :id, Serial
belongs_to :owner, 'A'
end
With this change, I only see one relationship attribute created on B, and I'm able to save instances of B that I create.

One-to-one DataMapper association

I'm very new to DataMapper, and I'm trying to create models for the following scenario:
I've got a number of users (with a user name, password etc.), who can also be players or referees or both (so Single Table Inheritance is not an option). The base models would be:
class User
include DataMapper::Resource
property :id, Serial
# Other user properties go here
end
class Player
include DataMapper::Resource
property :id, Serial
# Other player properties go here
# Some kind of association goes here
end
class Referee
include DataMapper::Resource
property :id, Serial
# Other referee properties go here
# Some kind of association goes here
end
DataMapper.finalize
I'm not sure, though, what kinds of associations to add to Player and Referee. With belongs_to :user, multiple players can be associated with the same user, which doesn't make sense in my context. In RDBMS terms I guess what I want is a unique constraint on the foreign key in the Players and Referees tables.
How do I accomplish this in my DataMapper model? Do I have to perform the check myself in a validation?
There are different ways you could do this. Here's one option:
class User
include DataMapper::Resource
property :id, Serial
# Other properties...
has 1, :referee, :required => false
has 1, :player, :required => false
end
class Referee
include DataMapper::Resource
# DON'T include "property :id, Serial" here
# Other properties...
belongs_to :user, :key => true
end
class Player
include DataMapper::Resource
# DON'T include "property :id, Serial" here
# Other properties...
belongs_to :user, :key => true
end
Act on the referee/player models like:
u = User.create(...)
u.referee = Referee.create(...)
u.player = Player.create(...)
u.player.kick_ball() # or whatever you want to call
u.player.homeruns
u.referee.flag_play() # or whatever.
See if this works. I haven't actually tested it but it should be good.
The previous answer works other than :required => false is not recognized for has 1 properties.
It's also confusing because for has n properties, you can use new right on the property or otherwise treat it as a collection. In your example, you would be tempted to code
u = User.create ...
u.referee.create ...
But that fails in the case of has 1 because the property is a single value, which begins life as nil and so you have to use the method the previous answer indicates. Also, having to explicitly make the belongs_to association into the key is a little confusing.
It does seem to execute validations and have the right association actions (so u.save will also save the referred-to Referee). I just wish it were more consistent between has n and has 1.

DataMapper: one to many relationship with one of several models?

Here's my models:
class Item
include DataMapper::Resource
property :id, Serial
has 1, :firstitem
has 1, :seconditem
end
class FirstItem
include DataMapper::Resource
property :id, Serial
belongs_to :item
end
class SecondItem
include DataMapper::Resource
property :id, Serial
belongs_to :item
end
Now, my question is this - if I want FirstItem and SecondItem to be different models but want them both to potentially be part of Item (but only one of the two, so a record with FirstItem will not also have a SecondItem), I could make a has 1 relationship for both of them, and only one of them gets filled.
So in a relational database, does it make sense to do this? Is there a better, more efficient way of defining this relationship?
What you want is a polymorphic association, which sadly, DataMapper does not support. Try looking into ActiveRecord instead; you can easily use it with Sinatra.

Foreign keys and associations using DataMapper

I have read this page quite thoroughly:
http://datamapper.org/docs/associations
If the answer is on there, it's simply not expressed in a way I can understand.
I'm very confused about using setting up relationship via Datamapper. The datamapper site above is pretty much all I can find on the topic, and as I've said, it hasn't been particularly helpful.
For example, if I want to create something like the following:
Table: users
id (primary key)
name
Table: attributes
id (pk)
title
Table: user_attributes
id (pk)
user_id (fk to users.id)
attribute_id (fk to attributes.id)
value
This seems simple enough, but it has been prohibitively difficult. Everything I try gives me errors like No relationships named user_attributes or user_attribute in UserUserAttribute (DataMapper::UnknownRelationshipError)
Can someone please tell me the class definitions for this simple mapping, and perhaps point me to a better discussion of DataMapper associations? Below is some of what I've tried.
class User
include DataMapper::Resource
property :id, Serial, :key => true
property :name, String
has n, :user_attributes, :through=>:attribute
end
class Attribute
include DataMapper::Resource
property :id, Serial, :key => true
property :name, String
has n, :user_attributes, :through=>:user
end
class UserAttribute
include DataMapper::Resource
belongs_to :user
belongs_to :attribute
end
I think you're seeing things like UserUserAttribute because DataMapper is trying to auto-generate an anonymous join class.
Here's an article that describes how to make named many-to-many relationships in DataMapper
You would probably change the example something like this:
User -> User
Project -> Attribute
Collaboration -> UserAttribute
The issue is that your class is UserAttribute, and you're trying to name the relationships with user_attributes. Get rid of the underscore, and your issue will disappear (or add an underscore to the class name)

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.

Resources