1

我正在尝试创建一个新的用户组多对多关系。我正在使用这些 dataMapper 对象

module Core_authentication

  class User
    include DataMapper::Resource

    property :id, Serial
    property :username, String
    property :password, BCryptHash
    property :email, String
    property :created_at, DateTime
    property :updated_at, DateTime

    #Creating join tables to link to group and person information
    has n, :Person, :through => Resource
    has n, :Group, :through => Resource
  end  

  class Group
    include DataMapper::Resource

    property :id, Serial
    property :name, String

    #Another jointable link group to link to functions and classification levels
    has n, :Function, :through => Resource
    has n, :Classificationlevel, :through => Resource
  end  

  class Person
    include DataMapper::Resource

    property :id, Serial
    property :firstname, String
    property :lastname, String
    property :adress, String
    property :postcode, String
    property :telefoon, String
    property :created_at, DateTime
    property :updated_at, DateTime

  end  

  class Function
    include DataMapper::Resource

    property :id, Serial
    property :name, String

  end  

  class Classificationlevel
    include DataMapper::Resource

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

  end

end

以及这些代码来创建和填充表格

user = Core_authentication::User.create
user.username = params['username']
user.password = params['password']
user.email = params['email']
#user.save

group = Core_authentication::Group.first_or_create(:name => params['group'])
group.name = params['group']
group.save

user.Group << group

但是当我想尝试它给我这个错误

NoMethodError at /register
undefined method `group' for #<Core_authentication::User:0x007f96cc2bf920>

    file: App.rb
    location: block in <class:App>
    line: 46

因此,它在我需要将表连接到具有两个 ID 的表中时失败了。为什么它会这样做,并且 wat 是一个可能的解决方案?是我将 DataMapper 对象放在模块中的问题吗?

4

1 回答 1

1

经过大量尝试后修复了该问题通过使用 has n, :model, through => Resource并将其放置在两个模型类中已修复。

这将创建一个包含两个资源 ID 的连接表,这里是一个小示例。

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

  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

  end  

然后只需创建 2 个对象,然后通过链接这些对象

user.persons << person

然后保存

于 2013-12-02T08:42:33.670 回答