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

為{幸葍}努か 提交于 2019-12-08 05:26:56

问题


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:


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'



来源:https://stackoverflow.com/questions/4883643/rails-3-polymorphic-association-between-one-mongomapper-model-and-one-many-activ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!