【问题标题】:Foreign keys and associations using DataMapper使用 DataMapper 的外键和关联
【发布时间】:2011-11-05 16:28:51
【问题描述】:

我已经非常彻底地阅读了这个页面:

http://datamapper.org/docs/associations

如果答案就在那里,那根本不是以我能理解的方式表达的。

我对通过 Datamapper 使用设置关系感到非常困惑。上面的 datamapper 网站几乎是我能找到的关于该主题的所有内容,正如我所说,它并不是特别有用。

例如,如果我想创建如下内容:

表:users

id (primary key)
name

表:attributes

id (pk)
title

表:user_attributes

id (pk)
user_id (fk to users.id)
attribute_id (fk to attributes.id)
value

这看起来很简单,但是却非常困难。我尝试的一切都会给我带来错误,例如No relationships named user_attributes or user_attribute in UserUserAttribute (DataMapper::UnknownRelationshipError)

有人可以告诉我这个简单映射的类定义,或许可以让我更好地讨论 DataMapper 关联吗?以下是我尝试过的一些方法。

class User
  include DataMapper::Resource

  property :id,   Serial, :key => true
  property :name, String

  has n, :user_attributes, :through=>:attribute
end

class Attribute
  include DataMapper::Resource

  property :id,   Serial, :key => true
  property :name, String

  has n, :user_attributes, :through=>:user
end

class UserAttribute
  include DataMapper::Resource

  belongs_to :user
  belongs_to :attribute
end

【问题讨论】:

    标签: ruby datamapper ruby-datamapper


    【解决方案1】:

    我认为您会看到类似 UserUserAttribute 的内容,因为 DataMapper 正在尝试自动生成匿名连接类。

    这里有一篇文章介绍了如何制作named many-to-many relationships in DataMapper

    您可能会像这样更改示例:

    • 用户 -> 用户
    • 项目 -> 属性
    • 协作 -> 用户属性

    【讨论】:

    • 通过指定模型、父键和子键(名称选择不当),我正在慢慢让它工作。谢谢。
    【解决方案2】:

    问题是您的类是 UserAttribute,而您正试图用 user_attributes 命名关系。去掉下划线,你的问题就会消失(或者给类名加下划线)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      相关资源
      最近更新 更多