【问题标题】:How to make a Many-To-One relationship in DataMapper如何在 DataMapper 中建立多对一关系
【发布时间】:2017-03-24 20:19:13
【问题描述】:

我正在尝试在两个模型之间创建关联:

class Person
   include DataMapper::Resource
   property :id, Serial
   property :name, String
end

class Country
   include DataMapper::Resource
   property :id, Serial
   property :name, String
end

我只需要一个关于 Person 的简单关系(country_id)。

我的第一个想法是在 Person 上放置一个 has 1 属性:

class Person
   include DataMapper::Resource
   property :id, Serial
   property :name, String
   has 1, :country
end

Datamapper 没有在 Person 表上创建 country_id,而是在 Country 上创建了 person_id

为了得到我需要的东西,我必须把它反转:

class Country
   include DataMapper::Resource
   property :id, Serial
   property :name, String
   has 1, :person
end

这样我在 Person 表上得到了我的 country_id 字段,但这对我来说真的没有任何意义。

是我误解了什么还是有其他方法可以建立这种关联?

【问题讨论】:

  • 欢迎来到 Stack Overflow。这不是 Sinatra 的问题。仅仅因为一个特定的 gem 是您项目的一部分并不足以标记它;它也需要成为相关代码的一部分。这是一个 Datamapper 问题。

标签: ruby datamapper ruby-datamapper


【解决方案1】:

只要模型 A“拥有”模型 B(一个或多个),就将外键添加到模型 B。

它的另一面是“属于”——这就是你用外键放在模型上的东西。

我猜在 DataMapper 中您不必显式添加外键列,但如果您愿意,您仍然可以这样做。

# Person
property :country_id, Integer

由于 Person 中的外键,您将使用“属于”。这似乎与“拥有一个”相同,但事实并非如此。在一对一关系等特殊情况下,您通常只需要“拥有一个”。

# Person
belongs_to :country

# Country
has n, :people
# you could use has 1, :person if for some reason every country
# only had 1 person in it

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多