How can I use Mongoid and ActiveRecord in parallel in Rails 3?

后端 未结 4 1574
小鲜肉
小鲜肉 2021-02-01 18:25

I\'m using rails 3, and began my application with ActiveRecord. Now, I have many models, and the relations are starting to get complicated, and some could be more simply expres

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 19:12

    i created a module for spoofing the relation in active record models.

    module MongoRelations
      def belongs_to_mongo(name, options = {})
        id_name = "mongo_#{name}_id".to_sym
        mongo_model = options[:through] || "Mongo::#{name.to_s.camelize}".constantize
    
        define_method(name) do
          id = send(id_name)
          mongo_model.find(id) if id.present?
        end
    
        define_method("#{name}=") do |value|
          send("#{id_name}=".to_sym, value.try(:id).to_s)
        end
      end
    end
    

    In my SQL table, I name my mongo relations using the convention mongo_XXX_id, instead of XXX_id

    I also namespace all my mongo models under Mongo::

    in my active record model

    class Foo < ActiveRecord::Base
        belongs_to_mongo :XXX
    end
    

    which allows

    Foo.new.XXX = Mongo.find('123')
    Foo.XXX
    

    or

    Foo.new.XXX_id = '123'
    Foo.XXX
    

提交回复
热议问题