1

I have an mysql table called "info_item", which can be extended with a mongodb document:

class CreateInfoItems < ActiveRecord::Migration
  def change
    create_table :info_items do |t|
      t.integer     :machine_id
      t.binary      :external_id
      t.integer     :info_type_id
      t.timestamps null: false
    end
  end
end

The field "external_id" is going to be an id of a mongodb document.

How can I represent it in my model? I thought about an object which is inherited from ActiveRecord::Base and includes the Mongoid::Document:

class InfoItem < ActiveRecord::Base
end

class PhoneNumber < InfoItem
  include Mongoid::Document
end

Is it going to run? Do you have other ideas?

1 Answer 1

1

I think you're better off hooking them together by hand. Both ActiveRecord::Base and Mongoid::Document will try to define all the usual ORM-ish methods so they will be fighting each other; ActiveRecord::Base will also try to do STI with that set up and you don't have any use for STI here.

Don't use binary for the external_id, AR will probably end up trying to serialize the BSON::ObjectId into YAML and you'll end up with a bunch of confusing garbage. Instead, store the BSON::ObjectId as a 24 character string:

t.string :external_id, :limit => 24

and say things like:

info_item.external_id = some_mongoid_document.id.to_s

and manually implement the usual relation methods:

def external
  external_id ? WhateverTheMongoidClassIs.find(external_id) : nil
end

def external=(e)
  self.external_id = e ? e.id.to_s : nil
end

You might want to override external_id= to stringify inputs as needed and external_id to BSON::Object_id.from_string outputs too.

I work with mixed PostgreSQL and MongoDB apps and this is the approach I use, works fine and keeps everything sensible in both databases.

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

1 Comment

I think my approach will be staying with AR model and adding methods to fetch the mongo data. I'll update about my changes when done. Thanks for your tips!

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.