问题
I have a project which I have used Active Record and which I'd like to add some new features using MongoDB. Rather than re-invent the wheel and re-write my entire site, how can I integrate 2 models together, one which use MongoMapper and the other ActiveRecord (postgres).
I've found that others have done it successfully, but no examples:
http://groups.google.com/group/mongomapper/browse_thread/thread/ec5ad00e18e7dd2c/887b8b0b904a8f73?lnk=gst&q=activerecord#887b8b0b904a8f73
For example, I have an STI Mongo model(s) of Places which I want to relate to an existing ActiveRecord model of Locations... ie Cities. and a User model based on Authlogic... how can I use them in concert? I'd be grateful for a pointer or two in the right direction.
Thanks,
回答1:
This worked beautifully
places model
key :location_id, Integer, :required => true
def location
Location.find(location_id)
end
locations model
def self.find_places(id)
Property.find_by_location_id(id)
end
def find_places
Property.find_by_location_id(id)
end
回答2:
You can also use typecasting.
Instead of just storing the location_id in mongodb, you can implement to class methods, from_mongo
and to_mongo
, in the Location class to allow mongomapper to serialize each Location instance in a mongo safe-and-friendly manner.
Simple(istc) example:
Places model
key :location, Location, :required => true
Location model
def self.to_mongo(location)
location[:id]
end
def self.from_mongo(location_id)
find(location_id)
end
This, of course, is exactly the same example as in the previous answer. The cool thing here is that you can serialize a full string, with more data if needed, thus making it easier to query and retrieve data from mongo.
For instance, the location_id and coordinates, so you can mimic a geodb and map/reduce for places in the same latitude. (stupid example, I know)
Reference: More MongoMapper Awesomenes
来源:https://stackoverflow.com/questions/2258681/activerecord-and-mongo-mongo-mapper-bridge