我有两个相互联系的模型。
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将不会更新。
怎么做?
答案 0 :(得分:0)
找到自己的解决方案。
问题是我将has 1
与belongs_to
混为一谈。 has 1
实际上是一个one_to_many关系,尝试在MailAddress
模型上创建属性,而不是User
模型。
诀窍是:
belongs_to :primary_mail_address, MailAddress, required: false