Datamapper:为同一模型创建两个关系(有n并且有1)

时间:2012-11-15 14:23:27

标签: ruby-on-rails ruby-datamapper

我有两个相互联系的模型。

class User
  include DataMapper::Resource

  property :id, Serial
  has n, :mail_addresses
end

class MailAddress
  include DataMapper::Resource

  property :id, Serial
  property :email, String, :required => true, :unique => true, :format => :email_address

  belongs_to :user
end

现在我想向用户添加主邮件地址。所以它可以做像

这样的事情
some_user.primary_mail_address = some_user.mail_addresses.first

我一直试图在用户模型上做这样的事情,但没有任何运气。

property :primary_mail_address_id, Integer, required: false
has 1, :primary_mail_address, model: 'MailAddress', parent_key: [:primary_mail_address_id], child_key: [:id]

上述技巧允许我执行代码示例,但是当我这样做时,primary_mail_address_id将不会更新。

怎么做?

1 个答案:

答案 0 :(得分:0)

找到自己的解决方案。

问题是我将has 1belongs_to混为一谈。 has 1实际上是一个one_to_many关系,尝试在MailAddress模型上创建属性,而不是User模型。

诀窍是:

belongs_to :primary_mail_address, MailAddress, required: false