How can I get all field names of the Mongoid Docum

2019-03-11 02:11发布

问题:

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.

回答1:

Mongoid already provides you the attributes for an object:

Model.new.attributes

To get the names for these attributes:

Model.fields.keys


回答2:

Use the built-in method:

Model.attribute_names
# => ["_id", "created_at", "updated_at", "name", "address"]


回答3:

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.



回答4:

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"]