Created
March 13, 2019 20:11
-
-
Save enmachs/36e3bc6da369dc076555e15fb9b7ace1 to your computer and use it in GitHub Desktop.
Example in case of many_to_many association
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
| # 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