Skip to content

Instantly share code, notes, and snippets.

@jponc
Created May 18, 2015 11:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jponc/0fbaf4b5aa4ad7cafa9e to your computer and use it in GitHub Desktop.
Save jponc/0fbaf4b5aa4ad7cafa9e to your computer and use it in GitHub Desktop.
Creating basic association between ActiveRecord models and Mongoid documents
# Original source: http://hashrocket.com/blog/posts/bridging-activerecord-and-mongoid
class ActiveRecord::Base
def self.has_many_documents(association_name)
class_eval %<
def #{association_name}
#{association_name.to_s.singularize.classify}.where(#{name.underscore}_id: id)
end
>
end
def self.has_one_document(association_name)
class_eval %<
def #{association_name}
#{association_name.to_s.singularize.classify}.where(#{name.underscore}_id: id).first
end
>
class_eval %<
def create_#{association_name} (new_attributes = {})
#{association_name.to_s.singularize.classify}.create(new_attributes.merge(#{name.underscore}_id: id))
end
>
end
end
module Mongoid::ActiveRecordBridge
extend ActiveSupport::Concern
included do
def self.belongs_to_record(association_name, options={})
association_class = options[:class_name] || association_name.to_s.singularize.classify
class_eval %<
field :#{association_name}_id, type: Integer
index(#{association_name}_id: 1)
def #{association_name}
@#{association_name} ||= #{association_class}.where(id: #{association_name}_id).first if #{association_name}_id
end
def #{association_name}=(object)
@#{association_name} = object
self.#{association_name}_id = object.try :id
end
>
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment