benams
benams

Reputation: 4656

rails model mixed of mongodb and mysql

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?

Upvotes: 1

Views: 459

Answers (1)

mu is too short
mu is too short

Reputation: 434965

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.

Upvotes: 1

Related Questions