Created
May 18, 2015 11:53
-
-
Save jponc/0fbaf4b5aa4ad7cafa9e to your computer and use it in GitHub Desktop.
Creating basic association between ActiveRecord models and Mongoid documents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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