Rails 3 Polymorphic Association between one MongoMapper model and one/many Active Record model/s
I have a Record model (Active Record) that stores some custom logs.
Record is in polymorphic association with all the other model in my app, and I can effectively log what I want hooking my Record methods in the other controllers.
What I need:
To have the logs in a separate database.
So I have to:
Be able to manage two different databases in开发者_JAVA百科 my apllication (one is Postgres/ActiveRecord and the other one is MongoDB/MongoMapper)
Generate a polymorphic association between my Record model, now with MongoMapper, and the rest of my Active Record models.
That way I can persist my logs to the MongoDB database.
Thanks.
Yes this can be done.
To create a polymorphic association you need both the class and an id. Idiomatically the fields will be named <assoc>_type
and <assoc>_id
‡. You will need to do some wiring up to make everything work.
- Create a MongoMapper::Document Class with the keys
<assoc>_type
and<assoc>_id
with the correct types (I believe MongoMapper allowsClass
as a key type) along with any other keys you may need. Define the method
<assoc>
and<assoc>=
def assoc assoc_type.find(assoc_id) end def assoc=(input) assoc_type = input.class #STI makes this more complicated we must store the base class asspc_id = input.id end
Possibly add a method to your ActiveRecord models allowing them to access you MongoMapper logging class. If there are a lot, you may want to build a module and include it in all the classes that need that kind of functionality.
‡ replace with something meaningful for you application like 'reference' or 'subject'
精彩评论