views:

271

answers:

1

Hello. I`m having trouble associating models in DataMapper. Its really simple, but i just can get the idea.

So, i have 2 tables:

1. Books
-> id
-> title
-> publisher_id

2. Publishers
-> id
-> title

The classes:

class Book
  property :id, Serial
  property :title, String
  property :publisher_id, Integer
end

class Publisher
  property :id, Serial
  property :title, String
end

So, the question is: How can i connect publisher to book? It is 1-to-1 relationship, and the whole thing supposed to look like this:

p = Book.get(12345).publisher

Sorry, maybe it is stupid. But i just cant figure out what kind of declaration i should use.

+2  A: 

Haha, im crazy idiot sitting at 2 in the morning. Always happening to me, when i ask somethis - suddenly find answer for my question myself.

It is incorrect, there is one-to-many relationship. So, it is simple as sun in the sky:

class Book
  property :id, Serial
  property :title, String
  property :publisher_id, Integer

  belongs_to :publisher
end

class Publisher
  property :id, Serial
  property :title, String

  has n, :books
end

That`s it. It might be helpful to somebody.

In both ActiveRecord and DataMapper, the table with the foreign key is represented by a class with a belongs_to association; the opposite end of the relationship is represented by some form of a "has" association. In ActiveRecord, this can be either "has_one" or "has_many"; in DataMapper, "has (arity)", where arity can be any number (i.e. has 1), range (has 2..4) or infinity (has n).
Greg Campbell