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

Yuri Sidorov picture Yuri Sidorov · Aug 10, 2011 · Viewed 12.6k times · Source

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 to write in backend/resourse_helper.rb

module Backend::ResourceHelper

  def attributes
    resource_class.attribute_names - %w(id created_at updated_at)
  end

end

I get the following error:

undefined method `attribute_names' for Backend::User:Class

(I rooted backend to "backend/users#index"). Backend::User inherits from User:

class User
  include Mongoid::Document

  devise_for :users

  field :name
  field :address
end

I just need a list of fields for that User:Class, as I guess (i.e. ["email", "name", "address", ...]), but I broke my head trying to find how.

Answer

Ryan Bigg picture Ryan Bigg · Aug 10, 2011

Mongoid already provides you the attributes for an object:

Model.new.attributes

To get the names for these attributes:

Model.fields.keys