1

I have two database in one app

  1. Postgres
  2. MongoDB

Except one model, all models are in Postgres Model name Message is in MongoDB as following

  1. message.rb - MongoDB

    class Message
      include Mongoid::Document
    
      field :content,         type: String
      field :user_id,         type: Integer
    end
    
  2. user.rb - Postgres

    class User < ApplicationRecord
    end
    

Now I want to associate user model with message model, to perform eagerloading.

If I write belongs_to :user, and then perform Message.last.user then following error will raise

NoMethodError (undefined method `_association' for []:Array)

Is there anyway to fix this issue?

1 Answer 1

3

You can't really make cross-database associations like that. But, depending on how much of the association you need, it might be easy to fake it:

class Message
  include Mongoid::Document

  field :content,         type: String
  field :user_id,         type: Integer

  def user
    User.find(user_id)
  end
end

If you're not sure about the validity of your user_ids then:

def user
  User.find_by(id: user_id)
end

might work better but you'll have to be prepared for nils to come out of some_message.user. You'll probably want to add some validations on user_id to make sure it really is the id of a User.

Of course, this chicanery won't help you propagate user deletions into MongoDB or support has_many :messages in User. You'd have to do those by hand as well but an after_destroy (or around_destroy) hook and a couple simple hand-written methods (and a solid test suite) can fill in those gaps.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply, as I have already done this, but this is not answer of my question, I want to define relationship between two model.
You can't build a cross-database relationship unless you do it by hand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.