这是情况.
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为nil.
我想知道在这里做什么是正确的事情.我应该让我的城市id是字符串还是BSON对象?或者我应该试图拦截update_attributes使mongoid store city_id为整数?我使用Integer作为城市的id的原因是因为我认为通过Integer搜索比搜索字符串要快.还有我有州和城市表,我想以可预测的方式匹配ids,所以我不想使用BSON randome密钥.
解决方法
@H_301_16@ 当然,如果你使用Mongoid,正确的方法是使用BSON对象作为ids.但是,如果您绝对需要使用整数作为城市ID,则可以使用这样的代码来模拟belongs_toclass Profile def city City.where(:id => self.city_id).last end def city=(new_city) self.city_id = new_city.id end end