List dynamic attributes in a Mongoid Model

后端 未结 6 1360
醉酒成梦
醉酒成梦 2021-02-06 15:49

I have gone over the documentation, and I can\'t find a specific way to go about this. I have already added some dynamic attributes to a model, and I would like to be able to it

6条回答
  •  粉色の甜心
    2021-02-06 16:24

    I wasn't able to get any of the above solutions to work (as I didn't want to have to add slabs and slabs of code to each model, and, for some reason, the attributes method does not exist on a model instance, for me. :/), so I decided to write my own helper to do this for me. Please note that this method includes both dynamic and predefined fields.

    helpers/mongoid_attribute_helper.rb:

    module MongoidAttributeHelper
      def self.included(base)
        base.extend(AttributeMethods)
      end
    
      module AttributeMethods
        def get_all_attributes
          map = %Q{
              function() {
                for(var key in this)
                {
                  emit(key, null);
                }
              }
            }
    
          reduce = %Q{
              function(key, value) {
                return null;
              }
            }
    
          hashedResults = self.map_reduce(map, reduce).out(inline: true) # Returns an array of Hashes (i.e. {"_id"=>"EmailAddress", "value"=>nil} )
    
          # Build an array of just the "_id"s.
          results = Array.new
          hashedResults.each do |value|
            results << value["_id"]
          end
    
          return results
        end
      end
    end
    

    models/user.rb:

    class User
       include Mongoid::Document
       include MongoidAttributeHelper
       ...
    end
    

    Once I've added the aforementioned include (include MongoidAttributeHelper) to each model which I would like to use this method with, I can get a list of all fields using User.get_all_attributes.

    Granted, this may not be the most efficient or elegant of methods, but it definitely works. :)

提交回复
热议问题