Skip to content

Instantly share code, notes, and snippets.

@lalitlogical
Last active December 15, 2018 18:11
Show Gist options
  • Save lalitlogical/26a2e376c7c5d8cd92aa0b4d0f6dbc15 to your computer and use it in GitHub Desktop.
Save lalitlogical/26a2e376c7c5d8cd92aa0b4d0f6dbc15 to your computer and use it in GitHub Desktop.
Custom has many through association in mongo db
module HasManyThrough
extend ActiveSupport::Concern
class_methods do
def define_through associations = {}
class_eval do
associations.each do |model, through_model|
model_name = model.to_s.underscore
define_method "#{model_name}_ids" do
eval("@#{model_name}_ids ||= #{through_model.to_s.underscore.pluralize}.distinct(:#{model_name}_id).compact")
end
define_method "#{model_name.pluralize}?" do
eval("#{model_name}_ids.present? ? #{model.to_s}.in(id: #{model_name}_ids).count != 0 : false")
end
define_method "#{model_name.pluralize}" do
eval("#{model_name}_ids.present? ? #{model.to_s}.in(id: #{model_name}_ids) : []")
end
end
end
end
end
end
# example model for using above module
# creating all model here
class DeveloperSkill
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :skill
belongs_to :developer
end
class Skill
include Mongoid::Document
include Mongoid::Enum
# included the above module
include HasManyThrough
has_many :developer_skills, dependent: :destroy
define_through({Developer: :DeveloperSkill})
# above will provide virtual association like below
# has_many :developers
end
class Developer
include Mongoid::Document
include Mongoid::Timestamps
# included the above module
include HasManyThrough
has_many :developer_skills, dependent: :destroy
define_through({Skill: :DeveloperSkill})
# above will provide virtual association like below
# has_many :skills
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment