Ruby on rails 如何获取Mongoid文档的所有字段名?
我正在构建后端系统,正如Iain Hecker的教程中所写的:我试图用Mongoid将其适应MongoDB 所以当我需要在backend/resource_helper.rb中编写时Ruby on rails 如何获取Mongoid文档的所有字段名?,ruby-on-rails,ruby,mongodb,mongoid,Ruby On Rails,Ruby,Mongodb,Mongoid,我正在构建后端系统,正如Iain Hecker的教程中所写的:我试图用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 `attr
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
(我将后端根目录设置为“后端/用户#索引”)。
后端::用户从用户继承:
class User
include Mongoid::Document
devise_for :users
field :name
field :address
end
我只需要该用户的字段列表:Class,正如我所猜测的(例如,[“email”、“name”、“address”、…]),但我绞尽脑汁想知道怎么做 使用
属性\u名称
,您的思路是正确的。我想你只需要确保你把你的模块放在正确的地方。例如,如果您有相同的模块:
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”]
Mongoid已经为您提供了对象的属性:
Model.new.attributes
要获取这些属性的名称,请执行以下操作:
Model.fields.keys
需要注意的一点是Model.fields.keys将只列出在Model类中定义的字段键。如果使用动态字段,则不会显示这些字段。Model.attributes.keys还将包括您使用过的任何动态字段的属性键。使用内置方法:
Model.attribute_names
# => ["_id", "created_at", "updated_at", "name", "address"]
不,这不起作用,它为User:Class`返回相同的
undefined方法
attributes'。如果包含Backend::resourceheloper
,那么attributes
方法就不会来自于此。将模块包含到类中将使该模块的方法可用于类的实例,而不是类本身。谢谢你,Ryan。我应该写extend
(更新)。另外,我的回答假设尤里在和全班同学一起工作。依我看,要求实例化该类是一个不合理的解决方案。根据给定示例的上下文以及报告的错误消息,我假设Yuri在这里使用的是一个类,而不是一个实例。如果这是真的,那么要求他实例化这个类似乎是不必要的。@Bloudermilk:没错。我已将此答案更新为现在使用Model.fields.keys
,因为这将返回正确的字段。谢谢你,Ryan!你的解决方案对我有效。我删除了Backend::User并编写了a=[];resource|class.all.collect{r|r.fields.keys.each{k|a@Yuri:首先,我不会调用变量a
。尝试给它一个更具描述性的名称。fields=resource|class.all.collect{r|r.fields.keys}-%w(|id |类型在更新时创建,在加密后创建)
将是我写这篇文章的方式。@Ryan Bigg:这个答案对我帮助很大。我想知道我们是否可以找到字段数据类型以及它的名称。Model.attributes.keys
不起作用,并抛出未定义的方法属性'
错误。