如何将Mongoid foreign_key保存为整数或保持父模型具有Integer id

时间:2012-01-31 17:47:02

标签: ruby ruby-on-rails-3 mongoid

情况如下。

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密钥。

1 个答案:

答案 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