ruby-on-rails - 如何获取 Mongoid 文档的所有字段名称?

标签 ruby-on-rails ruby mongodb mongoid

我正在构建后端系统,如 Iain Hecker 的教程中所述:http://iain.nl/backends-in-rails-3-1我尝试使用 Mongoid 使其适应 MongoDB。

所以当我需要写在 backend/resource_helper.rb 中时

module Backend::ResourceHelper

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

end

我收到以下错误:

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

(我将后端 Root 到“后端/用户#索引”)。 Backend::User 继承自 User:

class User
  include Mongoid::Document

  devise_for :users

  field :name
  field :address
end

我只需要该 User:Class 的字段列表,正如我猜想的那样(即 [“email”、“name”、“address”、...]),但我想知道如何找到方法。

最佳答案

Mongoid 已经为您提供了对象的属性:

Model.new.attributes

要获取这些属性的名称:

Model.fields.keys

关于ruby-on-rails - 如何获取 Mongoid 文档的所有字段名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7004742/

相关文章:

python - 适用于 Windows 的 Mongodb 电机驱动程序

ruby-on-rails - 在 Rails 中创建 Action

sql - 使用rails include语法指定左连接条件

ruby - 如何进行排列以有效地定制输出

ruby-on-rails - 在 Ruby 中验证电子邮件地址的最佳/简单方法是什么?

python - 访问 Mongo 文档的 id 字段引发 "TypeError: need one of hex, bytes, bytes_le, fields, or int"

ruby-on-rails - 访问模型中的current_user

javascript - 如何使用 javascript 在 Rails 中单击按钮时渲染部分内容,而不是使用 Controller 中的方法?

ruby-on-rails - 在 has_many :through association, 用 lambda 替换条件

javascript - 使用 React.js 插入 MongoDB 文档