Suresh Pala
Suresh Pala

Reputation: 1

create association between mongoDB document model and Activerecord model in rails

I am using rails 7 application. I am connecting to 2 distinct databases like mysql and mongo. I have one model connecting to mysql and another model connecting to mongo. mysql model user { firstname lastname locationID }

Mongo model location { locationID locationname }

I would like to create model association between user and location (location ID as key)

how do I accomplish this?

has_one with class name is giving error like "Rails couldn't find a valid model for association. Please provide the :class_name option on the association declaration. If :class_name is already provided, make sure it's an ActiveRecord::Base subclass."

Upvotes: 0

Views: 205

Answers (1)

max
max

Reputation: 102250

This is not possible.

ActiveRecord is a ORM for Relational Database Management Systems (RDBMS) such as Postgres, SQLite, MySQL and Oracle. This are table based systems where relations between the tables consist of foreign key columns that point to other tables. ActiveRecord::Assocations are just a fancy construction on top of this concept which generate join queries and eager load data with SQL queries.

MongoDB is not a relational database - it's document oriented. It uses queries based on JavaScript instead of SQL. You cannot connect to it with ActiveRecord. Instead you would use Mongoid which is a Document-Object Mapper. Relations in MongoDB can consist of nesting documents inside of other documents.

The closest you're going to get to your idea is to store an ObjectID (the MongoDB equivent to a primary key) in the relational database and use that to manually fetch the record with Mongoid or vice versa.

But you should really reconsider the whole idea as there are going to be significant costs to this in terms of performance and developer time.

Upvotes: 0

Related Questions