我已经使用特定的父键和子键设置了以下模型:
class Province
include DataMapper::Resource
property :name_short, String, key: true, length: 2, unique: true
property :name_long, String, length: 1..50
has n, :municipalities, 'Municipality',
parent_key: [:name_short],
child_key: [:province]
end
class Municipality
include DataMapper::Resource
property :province, String, key: true, length: 2
property :name, String, key: true, length: 1..40
property :lat, Float
property :long, Float
property :current_population, Integer
belongs_to :province, 'Province',
parent_key: [:name_short],
child_key: [:province]
end
我创建关联的记录:
province = Province.get('BC')
municipality = province.municipalities.new(
name: '100 mile house',
lat: 51.23131,
long: 121.65489,
current_population: 0)
然后执行municipality.save
,它失败了,因为它试图保存的记录(见下文)试图使用整个省对象作为键,而不仅仅是 :name_short 字段。
#<Municipality @province=#<Province @name_short="BC" @name_long="British Columbia"> @name="100 mile house" @lat=51.64300975 @long=121.295022 @current_population=0>
我究竟做错了什么?
返回的save
错误是验证类型错误:
["Province must be at most 2 characters long", "Province must be of type String"]
嗯。再看看这个,我想知道 DataMapper 本身是否不强制引用完整性(通过将父键插入新的孩子),并且我可能必须通过自己设置市政府中的省字段来做到这一点?我会试一试......不,那没有解决它。
更新:奇怪,但是通过将以下to_s
方法添加到Province
类中,我摆脱了"Province must be at most 2 characters long"
错误 - 但仍然得到字符串错误:
def to_s
@short_name
end