Skip to content

Instantly share code, notes, and snippets.

@reddyonrails
Last active August 29, 2015 14:00
Show Gist options
  • Save reddyonrails/11276291 to your computer and use it in GitHub Desktop.
Save reddyonrails/11276291 to your computer and use it in GitHub Desktop.
Mongoid and Active record linked associations
#Extended this gist https://gist.github.com/knapo/8897592
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,options={})
association_class = unless options.empty?
options[:class_name]
else
association_name.to_s.singularize.classify
end
if options.present? && options[:conditions].present?
class_eval %<
def #{association_name}
#{association_class}.#{options[:conditions]}.where(#{name.underscore}_id: id).first
end
def #{association_name}=(object)
@#{association_name} = object
self.#{association_name}_id = object.try :id
end
>
else
class_eval %<
def #{association_name}
#{association_class}.where(#{name.underscore}_id: id).first
end
def #{association_name}=(object)
@#{association_name} = object
self.#{association_name}_id = object.try :id
end
>
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
def self.has_one_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
class Profile < ActiveRecord::Base
has_many_documents :users
has_one_document :admin, {:conditions => "where(admin: true)" , :class_name => "User" }
end
class User
belongs_to_record :profile
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment