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

后端 未结 4 1603
小鲜肉
小鲜肉 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:09

    What I did was just mock the relationship with methods in each the AR model and the Mongoid model like so.

    # visit_session.rb
    class VisitSession
      include Mongoid::Document
      include Mongoid::Timestamps
    
      field :user_id, type: Integer
      index({user_id: 1},{name: :user_id_index})
    
      # Mock a belongs_to relationship with User model
      def user
        User.find(self.user_id)
      end
    end
    
    # user.rb
    class User < ActiveRecord::Base
    
      # Mock a has_many relationship with VisitSession Mongoid model
      def visit_sessions
        VisitSession.where(user_id: self.id)
      end
    end
    

    Of course you won't have all the AR methods on VisitSession Mongoid model but you'll at least be able to mock the relationship between the two fairly well.

    Hope this helps.

提交回复
热议问题