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

你说的曾经没有我的故事 提交于 2019-12-06 16:24:11

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'

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