【问题标题】:How to save Mongoid foreign_key as integer or keep the parent model have Integer id如何将 Mongoid foreign_key 保存为整数或保持父模型具有 Integer id
【发布时间】:2012-01-31 17:47:02
【问题描述】:

情况是这样的。

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 随机键。

【问题讨论】:

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


    【解决方案1】:

    当然,如果您使用 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
    

    【讨论】:

    • 这看起来很有希望。但如果问题涉及许多表和许多属性,则可能需要添加很多方法。如果我将这些属性声明为整数,如果我可以自动将字符串参数转换为整数,那就太好了。猴子修补到 Mongoid,也许?
    • bson 对象有什么问题?
    • 我正在移植城市状态表。我希望整数成为州的 id,所以我的城市指的是正确的州。我想我可以使用单独的属性作为外键,然后我不会介意 bson 作为 id。
    猜你喜欢
    • 1970-01-01
    • 2015-11-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多