Rails 3 Polymorphic Association between one MongoMapper model and one/many Active Record model/s

878 views Asked by At

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:

  1. Be able to manage two different databases in my apllication (one is Postgres/ActiveRecord and the other one is MongoDB/MongoMapper)

  2. 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.

1

There are 1 answers

1
John F. Miller On BEST ANSWER

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.

  1. Create a MongoMapper::Document Class with the keys <assoc>_type and <assoc>_id with the correct types (I believe MongoMapper allows Class as a key type) along with any other keys you may need.
  2. 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
    
  3. 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'