0

我有两个模型,它们相互链接。

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 不会得到更新。

怎么做?

4

1 回答 1

0

找到了自己的解决方案。

问题是我has 1belongs_to. has 1实际上是一个 one_to_many 关系,它试图在模型上创建属性MailAddress,而不是在User模型上。

诀窍是:

belongs_to :primary_mail_address, MailAddress, required: false
于 2012-11-15T20:34:46.223 回答