rubydatamapperruby-datamapper

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

Solution

  • 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: