【问题标题】:How can I get all field names of the Mongoid Document?如何获取 Mongoid 文档的所有字段名称?
【发布时间】:2011-10-23 16:49:52
【问题描述】:

我正在构建后端系统,正如 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

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

class User
  include Mongoid::Document

  devise_for :users

  field :name
  field :address
end

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

【问题讨论】:

    标签: ruby-on-rails ruby mongodb mongoid


    【解决方案1】:

    attribute_names 让您走在正确的轨道上。我认为您只需要确保将模块包含在正确的位置即可。例如,如果您有相同的模块:

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

    你的班级应该是这样的:

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

    然后调用User.attributes 应该返回["name", "address"]

    【讨论】:

    • 不,这不起作用,它为 User:Class ` 返回相同的 undefined method attributes'。
    • 如果你 包括 Backend::ResourceHelper 那么attributes 方法就不会来自那里。将模块包含到类中将使该模块的方法可用于类的实例,而不是类本身。
    • 谢谢你,瑞恩。我应该写extend(更新)。另外,我的回答假设 Yuri 正在与班级一起工作。要求类的实例化将是一个不合理的解决方案,IMO。
    【解决方案2】:

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

    Model.new.attributes
    

    要获取这些属性的名称:

    Model.fields.keys
    

    【讨论】:

    • 根据给定示例的上下文以及报告的错误消息,我假设 Yuri 在这里使用的是一个类,而不是一个实例。如果这是真的,要求他实例化这个类似乎是不必要的。
    • @Bloudermilk:没错。我已将此答案更新为现在使用Model.fields.keys,因为这将返回正确的字段。
    • 谢谢你,瑞恩!你的解决方案对我有用。我删除了 Backend::User 并写了a = []; resource_class.all.collect { |r| r.fields.keys.each { |k| a << k } }; a.uniq - %w(_id _type created_at updated_at encrypted_password)。你不知道我该如何重构这个字符串吗?我对 ruby​​ 不太熟悉)
    • @Yuri:首先我不会调用变量a。尝试给它一个更具描述性的名称。 fields = resource_class.all.collect { |r| r.fields.keys } - %w(_id _type created_at updated_at encrypted_password) 就是我写这篇文章的方式。
    • @Ryan Bigg:这个答案对我帮助很大。我想知道我们是否可以找到字段数据类型以及找到它的名称。
    【解决方案3】:

    需要注意的一点是 Model.fields.keys 只会列出在 Model 类中定义的字段键。如果您使用动态字段,它们将不会显示。 Model.attributes.keys 还将包含您使用的任何动态字段的属性键。

    【讨论】:

    • Model.attributes.keys 不起作用并抛出 undefined method attributes' 错误。
    【解决方案4】:

    使用内置方法:

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

    【讨论】:

      猜你喜欢
      • 2019-12-29
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-18
      • 2022-08-24
      相关资源
      最近更新 更多