randombits
randombits

Reputation: 48450

Rails 3: Migrating a model to MongoDB

I have a few models in my existing Rails 3 app that are completely non-relational to the other models in the application's ecosystem. The underlying data is incredibly large and it would benefit in being moved from my relational db (MySQL) to a non-relational document data store, such as MongoDB. The problem I currently have is that the model is instantiated in several places in my code base using Foo.create, Foo.new etc. My question(s) are the following:

Upvotes: 2

Views: 2088

Answers (3)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

There's no inherent problem in having some classes in ActiveRecord and some in Mongoid, just transfer the data over.

This is a rather simplistic example, but below you would still be able to say @account.transactions

class Account < ActiveRecord::Base

  def transactions
    Transaction.where(:account_id=>self.id).all
  end

end

class Transaction
  include Mongoid::Document
  field :account_id, :type=>Integer

  def account
    Account.find(account_id)
  end
end

Upvotes: 2

oma
oma

Reputation: 40780

1) Just do it, using mongoid or mongo_mapper. Both are great!

2 ) NO! Replace ActiveRecord superclass with that of mongoid or mongo_mapper.

The only difficult thing about polyglot persistence is to remember the word, polyglot. Don't over-complicate. The models that inherit ActiveRecord are mapped to the SQL-db, the models that don't inherit it, are not. Simple as that. Same with the models that inherit the Mongo-ORM-class, only they are mapped to MongoDB.

I use postgreSQL alongside MongoDB (mongo_mapper). One awesome thing for everybody to try out, is storing errors in Mongo docs. Beats *.log files.

Final note: Having Foo.create and Foo.new at multiple places is a code smell and you should probably refactor according to DRY and SRL. Just a friendly note:)

Upvotes: 3

blu
blu

Reputation: 13175

Look at mongoid, an orm for mongodb. It uses ActiveModel and can essential behave just like your ActiveRecord based models. Once you include the mongoid document class in your model, add the fields and config the connection it should be fairly transparent.

Upvotes: 1

Related Questions