2013-12-11 1 views
0

На данный момент у меня есть модель базы данных и может заселить модели с данными:DataMapper многие-ко-многим ассоциации

user.persons << person 
    group.functions << function 
    group.classificationlevels << clasfication 
    user.groups << group 

Эти модели, которые я использую в настоящее время для получения данных, связанных с друг друг:

module Core_authentication 

    class User 
    include DataMapper::Resource 

    property :id, Serial 
    property :username, String, :required => true, :unique => true 
    property :password, BCryptHash, :required => true 
    property :email, String, :format => :email_address, :required => true 
    property :created_at, DateTime 
    property :updated_at, DateTime 

    #Creating join tables to link to group and person information 
    has n, :persons, :through => Resource 
    has n, :groups, :through => Resource 

    def username= new_username 
     super new_username.downcase 
    end 

    end 

    class Group 
    include DataMapper::Resource 

    property :id, Serial 
    property :groupname, String, :required => true 

    #Another jointable link group to link to functions and classification levels 
    has n, :functions, :through => Resource 
    has n, :classificationlevels, :through => Resource 
    has n, :users, :through => Resource 

    def groupname= new_group 
     super new_group.downcase.capitalize! 
    end 
    end 

    class Person 
    include DataMapper::Resource 

    property :id, Serial 
    property :firstname, String 
    property :lastname, String, :required => true 
    property :adress, String 
    property :postcode, String, :length => 6, :required => true 
    property :telefoon, String 
    property :created_at, DateTime 
    property :updated_at, DateTime 

    has n, :users, :through => Resource 

    def firstname= new_firstname 
     super new_firstname.downcase.capitalize! 
    end 

    def lastname= new_lastname 
     super new_lastname 
    end 

    end 

    class Function 
    include DataMapper::Resource 

    property :id, Serial 
    property :name, String 

    has n, :groups, :through => Resource 

    end 

    class Classificationlevel 
    include DataMapper::Resource 

    property :id, Serial 
    property :levelcode, Integer 
    property :name, String 

    has n, :groups, :through => Resource 

    end 

end 

Я хочу, чтобы получить группы пользователя, они являются членами, а уровень классификации, связанный с каждой группой.

Я попробовал несколько способов сделать это, а также просмотрел в Интернете, но я не могу найти четкое объяснение того, как я должен это делать, и поэтому я не могу заставить его работать.

ответ

2

documentation for Datamapper (раздел для «Имеет, и принадлежит, многие (или многие-ко-многим)») имеет некоторые намеки, вот упрощенный пример ваших моделей:

require 'sqlite3' 
require 'dm-core' 
require 'dm-sqlite-adapter' 
require 'dm-migrations' 

DataMapper.setup(:default, 'sqlite3:m2m.sqlite3') 

class User 
    include DataMapper::Resource 
    property :id, Serial 
    has n, :persons, :through => Resource # => PersonUser 
    has n, :groups, :through => Resource # => GroupPerson 
end 

class Group 
    include DataMapper::Resource 
    property :id, Serial 
    has n, :functions, :through => Resource # => FunctionGroup 
    has n, :classificationlevels, :through => Resource # => GroupClassificationlevel 
    has n, :users, :through => Resource # => GroupUser 
end 

class Person 
    include DataMapper::Resource 
    property :id, Serial 
    has n, :users, :through => Resource # => PersonUser 
end 

class Function 
    include DataMapper::Resource 
    property :id, Serial 
    has n, :groups, :through => Resource # => FunctionGroup 
end 

class Classificationlevel 
    include DataMapper::Resource 
    property :id, Serial 
    has n, :groups, :through => Resource # => GroupClassificationlevel 
end 

И пример используя их (если вы поместите оба эти фрагмента в файл и запустите их, вы увидите вывод):

DataMapper.finalize 

DataMapper.auto_migrate! 

user = User.create 
group = Group.create 

# link them by adding to the relationship 
user.groups << group 
user.save 

p user.groups # => [#<Group @id=1>] 
+0

Спасибо, я наконец понял! Но если я работаю в пространстве имен модулей, он будет работать одинаково? –

+0

Объекты должны быть одинаковыми, вам просто нужно будет префикс имени модуля. – phillbaker