1

I am a total beginner at DataMapper, and have two models:

class ThirdPartyAccount
    include DataMapper::Resource
    property :access_token,     String, :length => 500
    belongs_to :user
end

class User
    include DataMapper::Resource
    property :id,           Serial
    property :first_name,    String
    has n, :third_party_accounts, :through => Resource
end

Looking at the SQL logs, it appears to create two tables- users, third_party_accounts and third_party_account_users to join the two. It doesn't appear that the last table is needed- surely the third_party_account table just needs to use it's user_id field to map directly to the user table? Have I accidentally created a many-to-many relationship here?

Alastair
  • 5,894
  • 7
  • 34
  • 61

1 Answers1

1

It's due to this line:

has n, :third_party_accounts, :through => Resource

:through => Resource tells DataMapper to that it's a "has-and-belongs-to-many" relation (each 3rd party account belongs to multiple users and each user has multiple 3rd party accounts), which requires an intermediate table. If this is just a has-many relation (each user has many 3rd party accounts, but each account only belongs to one user), you should just use:

Class User
  ...
  has n, :third_party_accounts
end

See http://datamapper.org/docs/associations.html for more info.

AlexQueue
  • 6,353
  • 5
  • 35
  • 44
  • Perfect, thanks. Not sure where I'd read the ```Resource``` stuff before- although I know SQL and most languages well, there's evidently still some semantics to DataMapper I need to work out. – Alastair May 18 '13 at 03:33