ben*_*ang 12 ruby mongoid ruby-on-rails-3
情况就是这样.
user embed_one profile
profile belongs_to city
Run Code Online (Sandbox Code Playgroud)
我填写了一张城市表
id as Integer
name as String
Run Code Online (Sandbox Code Playgroud)
现在我正在
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密钥.
当然,如果你使用 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
Run Code Online (Sandbox Code Playgroud)