情况如下。
user embed_one profile
profile belongs_to city
我用
填充了一张城市表id as Integer
name as String
现在我在做
user.update_attributes(:profile_attributes{:city_id=>"5"})
模拟浏览器表单提交。然后我检查user.profile
我看到city_id存储为字符串。这使我的user.profile.city
给出无效。
我想知道在这里做什么是正确的。我应该让我的城市ID是字符串还是BSON对象?或者我应该尝试拦截update_attributes以使mongoid存储city_id为整数?我使用Integer作为城市id的原因是因为我认为通过Integer搜索比搜索字符串更快。而且我还有状态和城市表,我希望以可预测的方式匹配ID,所以我不想使用BSON randome密钥。
答案 0 :(得分:0)
当然,如果你使用Mongoid,正确的方法是使用BSON对象作为id。但是如果你绝对需要使用整数作为城市ID,你可以用这样的代码模拟belongs_to
class Profile
def city
City.where(:id => self.city_id).last
end
def city=(new_city)
self.city_id = new_city.id
end
end