DataMapper`对于不同类型的模型具有n`

时间:2013-07-09 19:53:04

标签: ruby orm model datamapper ruby-datamapper

我想要一个具有不同类型has n的模型,例如:

class Blog
  include DataMapper::Resource

  property :id, Serial

  has 1, :owner   # of type user...
  has n, :authors # of type user...
end

class User
  include DataMapper::Resource

  property :id, Serial

  has n, :blogs # owns some number
  has n, :blogs # is a member of some number
end

但是,我不想使用Discriminator,因为那时我需要创建旧用户对象的新所有者或作者对象,这将是荒谬的。

我怎样才能最好地实现这一目标?

1 个答案:

答案 0 :(得分:0)

试试这个:

class User
  include DataMapper::Resource

  property :id, Serial

  has n, :blog_authors, 'BlogAuthor'
  has n, :authored_blogs, 'Blog', :through => :blog_authors, :via => :blog

  has n, :blog_owners, 'BlogOwner'
  has n, :owned_blogs, 'Blog', :through => :blog_owners, :via => :blog
end

class Blog
  include DataMapper::Resource

  property :id, Serial

  has n, :blog_authors, 'BlogAuthor'
  has n, :authors, 'User', :through => :blog_authors

  has 1, :blog_owner, 'BlogOwner'
end

class BlogAuthor
  include DataMapper::Resource

  belongs_to :blog, :key => true
  belongs_to :author, 'User', :key => true
end

class BlogOwner
  include DataMapper::Resource

  belongs_to :blog, :key => true
  belongs_to :owner, 'User', :key => true
end