【问题标题】:Data Mapper Associations - what code?数据映射器关联 - 什么代码?
【发布时间】:2016-06-19 08:44:58
【问题描述】:

我查看了 DataMapper 文档,但正在努力了解如何执行此操作。我有两个表,我只是希望将 User 表中的 'handle' 属性作为一列添加到 Peeps 表中 - 如下所示?

【问题讨论】:

    标签: ruby datamapper


    【解决方案1】:

    文档:http://datamapper.org/docs/associations.html 自定义关联部分。

    class User
      ...
      has n, :peeps, 'Peep',
        :parent_key => [ :handle ],      # local to this model (User)
        :child_key  => [ :user_handle ]  # in the remote model (Peep)
    end
    
    class Peep
      ...
      belongs_to :user, 'User',
        :parent_key => [ :handle ],      # in the remote model (Peep)
        :child_key  => [ :user_handle ]  # local to this model (User)
    end
    

    【讨论】:

    • 谢谢你——当我尝试用 rake 运行 auto_migrate 时,它​​出现了以下错误,有什么想法吗? rake db:auto_migrate rake aborted! DataObjects::SyntaxError: ERROR: there is no unique constraint matching given keys for referenced table "users"
    • 错误所说的实际上是您必须为 handle 键添加唯一约束。或者假设用户 A 和用户 B 都有一个句柄 larry,那么一个具有 user_handle 值的窥视 larry 将不知道谁是它的真正用户。您应该做的只是创建另一个迁移以添加唯一约束。
    • 好吧,那太好了——我在手柄上添加了一个独特的:true 属性,这似乎有效。干杯。由于建立了这种关联,我现在无法将我的“窥视”添加到数据库中,所以我会解决这个问题。关联通常会破坏向数据库添加数据的功能吗?
    • @sdawes 我不这么认为。我认为您唯一应该关注的是user_handle实际上存在于用户表中,除此之外,我认为一切都很好。
    • 同时,我想你可以接受这个答案,:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    相关资源
    最近更新 更多