Skip to content

Instantly share code, notes, and snippets.

@enmachs
Created March 13, 2019 20:11
Show Gist options
  • Select an option

  • Save enmachs/36e3bc6da369dc076555e15fb9b7ace1 to your computer and use it in GitHub Desktop.

Select an option

Save enmachs/36e3bc6da369dc076555e15fb9b7ace1 to your computer and use it in GitHub Desktop.
Example in case of many_to_many association
# Method
def has_many_mongoid(field, options)
raise ArgumentError, "inverse_of missing" unless options[:inverse_of].present?
foreign_key = "#{options[:inverse_of]}_id"
through = options[:through]
# register_dependent_pg field, options.delete(:dependent), foreign_key
has_many field, options
klass = (through ? through : options[:class_name]).constantize
define_method field.to_sym do
klass_where = klass.where(foreign_key => id)
klass_where = klass_where.flat_map(&field.to_s.singularize.to_sym) if through
id ? klass_where : super()
end
end
# Usage
has_many_mongoid :users, through: 'Pg::CompetitionUser', inverse_of: :competition, class_name: 'Db::User'
# NOTE: This way I think consume more resource
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment