我使用的是 Rails 3,并使用 ActiveRecord 开始我的应用程序。现在,我有很多模型,并且关系开始变得复杂,有些可以用面向文档的结构更简单地表达,所以我想尝试迁移到 MongoDB 并使用 Mongoid。
我一直听说您不必使用所有 MongoDB 或什么都不使用,但您可以在迁移时并行使用两者。但我不知道如何从文档中解决这个问题。
例如,我有:
class User < ActiveRecord::Base
has_many :items
has_many :products, :through => :items
end
class Product < ActiveRecord::Base
has_many :items
end
class Item < ActiveRecord::Base
belongs_to :user
belongs_to :product
# alot of data that fits a hierarchical document-oriented structure
end
理想情况下,我想首先用 Mongoid 文档替换我的 Item activerecord 模型,这样我的项目就存储在 MongoDB 中,而我的项目则存储在 MongoDB 中。Users
and Products
可以保留在 mySQL DB 中
问题是,我不知道该怎么做。我以正确的方式处理这件事吗?
也许另一种选择是保留基础 AR 物品
class Item < ActiveRecord::Base
has_one :mongodb_item ?? # I know this is wrong
end
class MongodbItem
include Mongoid::Document
belongs_to AR_Item ??? # I know this is also wrong
end
Thanks!
我所做的只是模拟 AR 模型和 Mongoid 模型中方法的关系,如下所示。
# visit_session.rb
class VisitSession
include Mongoid::Document
include Mongoid::Timestamps
field :user_id, type: Integer
index({user_id: 1},{name: :user_id_index})
# Mock a belongs_to relationship with User model
def user
User.find(self.user_id)
end
end
# user.rb
class User < ActiveRecord::Base
# Mock a has_many relationship with VisitSession Mongoid model
def visit_sessions
VisitSession.where(user_id: self.id)
end
end
当然,您不会拥有 VisitSession Mongoid 模型上的所有 AR 方法,但您至少能够很好地模拟两者之间的关系。
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)