khiav223577 / deep_pluck

Allow you to pluck attributes from nested associations without loading a bunch of records.
MIT License
460 stars 14 forks source link

Support for Mongoid #21

Closed berniechiu closed 1 year ago

berniechiu commented 6 years ago

Happy to see if we can support Mongoid in the future. Actually I can do it if I have some suggestions for the head start.

khiav223577 commented 6 years ago

Hi, I'm welcome to seeing any contributes to this :)

Not sure how to read data from Mongoid. But I think there are two core parts you need to modify: One of the core parts is in the do_query method which is responsible for the query condition. The other is in the load_data method where it plucks attributes from model. You may want to take a look at the gem pluck_all, inspired by this article and used for plucking attributes as hash, first.

And you have to modify the gemfiles and travis.yml if you want to run test cases with Mongoid. Take Postgresql for example:

.travis.yml

env: 
  - DB=mysql
  - DB=pg

3.2.gemfile

group :test do
  case ENV['DB']
  when "mysql"    ; gem 'mysql2' , '0.3.21'
  when "postgres" ; gem 'pg', '~> 0.18'
  end
end
khiav223577 commented 6 years ago

I added the support of mongoid to pluck_all, see https://github.com/khiav223577/pluck_all/pull/24.

The remain works are detecting the association between two mongoid documents and the association between mongoid document and activemodel. For example:

class Profile
  include Mongoid::Document

  field :user_id, type: Integer
  field :school_name, type: String
end

class User < ActiveRecord::Base
end

# The pseudo code of the flow:
# [1] users = User.pluck_all(:id, :account)
# [2] user_ids = get the ids from users
# [3] profiles = Profile.where(user_id: user_ids).pluck_all(:user_id, :school_name)
# [4] merge profiles to users by users' id and profiles' user_id
# [5] clean unneeded data

# Need to find out a way to know how to query the users and profiles: [1] and [3]
# This two methods may act as the core parts: #get_foreign_key, #get_primary_key
User.deep_pluck(:account, profile: :school_name)

Would you like to try it?

berniechiu commented 6 years ago

cool cool~ let me check check

berniechiu commented 6 years ago

While looking at your code, I would like to mark some TODOs first for the pluck_all, will be working on it these days maybe ~

TODO