Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 282
Yuri Sidorov Avatar asked Aug 10 '11 00:08

Yuri Sidorov


People also ask

How do I get field names in MongoDB?

You can use $getField to retrieve the value of fields with names that contain periods ( . ) or start with dollar signs ( $ ).

What is field name in MongoDB?

Field names are strings. Documents have the following restrictions on field names: The field name _id is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of any type other than an array.

How do I show columns in MongoDB?

In MongoDB, there is no concept of columns since MongoDB is schema-less and does not contain tables. It contains the concept of collections and a collection has different types of documents to store items. db. yourCollectionName.

How do I search in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.


1 Answers

Mongoid already provides you the attributes for an object:

Model.new.attributes

To get the names for these attributes:

Model.fields.keys
like image 141
Ryan Bigg Avatar answered Oct 21 '22 01:10

Ryan Bigg