How can I get all field names of the Mongoid Document?

前端 未结 4 607
孤街浪徒
孤街浪徒 2021-02-02 13:36

I\'m building backend system, as written in Iain Hecker\'s tutorial: http://iain.nl/backends-in-rails-3-1 and I try to adapt it to MongoDB with Mongoid.

So when I need t

相关标签:
4条回答
  • 2021-02-02 14:06

    Use the built-in method:

    Model.attribute_names
    # => ["_id", "created_at", "updated_at", "name", "address"]
    
    0 讨论(0)
  • 2021-02-02 14:06

    You're on the right track with attribute_names. I think you just need to make sure you're including your module in the proper place. For instance, if you had the same module:

    module Backend::ResourceHelper
      def attributes
        resource_class.attribute_names - %w(id created_at updated_at)
      end
    end
    

    Your class should look like so:

    class User
      include Mongoid::Document
      extend Backend::ResourceHelper
    
      devise_for :users
    
      field :name
      field :address
    end
    

    Then calling User.attributes should return ["name", "address"]

    0 讨论(0)
  • 2021-02-02 14:08

    Mongoid already provides you the attributes for an object:

    Model.new.attributes
    

    To get the names for these attributes:

    Model.fields.keys
    
    0 讨论(0)
  • 2021-02-02 14:08

    One thing to take note of is that Model.fields.keys will only list the field keys that are defined in the Model class. If you use dynamic fields they will not be shown. Model.attributes.keys will also include the attribute keys for any dynamic fields you have used.

    0 讨论(0)
提交回复
热议问题