If I use MongoDB with Rails, can I use Active Record associations?
Asked Answered
D

3

8

I am planning to build Rails app with mongoDb, but I don't know will I be able to use active record associations such as many-to-many etc.? Also, when I use mongoDb with rails, do I replace Active Record ORM with some other ORM for mongoDB?

Dola answered 29/2, 2016 at 18:54 Comment(0)
D
5

I believe you can use mongoid which works as an ODM - object document mapper.

Taken from the mongo docs

You can define associations where children are stored in a separate collection from the parent document like so:

 class Band
  include Mongoid::Document
  has_many :members
end

You can also define associations where the relation is embedded in the parent like so

class Person
  include Mongoid::Document
  embeds_many :addresses
end

Check the docs here for more - https://docs.mongodb.org/ecosystem/tutorial/mongoid-relations/

Disarm answered 29/2, 2016 at 19:24 Comment(0)
W
3

ActiveRecord will not work with Mongo. What you want to use instead is Mongoid, which is more or less the equivalent of ActiveRecord for Mongo.

Wrennie answered 29/2, 2016 at 19:24 Comment(0)
G
0

When using Mongoid as ODM instead of ActiveRecord as ORM, you won't be able to use ActionText, ActiveStorage and ActionMailbox since these cannot be used with Mongoid due to their reliance on ActiveRecord, as stated here.

If you still want to use these and/or other features of ActiveRecord, you may want to try this tutorial that relies only on the gem 'mongo' as database driver, instead of ripping out and replacing one of the core components of Rails.

Gymnasiast answered 18/3, 2024 at 21:25 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.