Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top