【发布时间】:2014-02-26 22:43:18
【问题描述】:
当我在 ItemHelper 类中运行 Item.where(:id => id) 的简单查询并返回时
[
{
JDPA: null,
_id: "530e45f43f72fb3dee000001",
category: null,
created_at: "2014-02-26T19:52:20Z",
creator: "5170547c791e4b1a16000001",
detail: "Detail",
event_id: "52d958e73f72fb1e1f000001",
image_content_type: null,
image_file_name: null,
image_file_size: null,
image_updated_at: null,
question: null,
section: null,
title: "Title",
updated_at: "2014-02-26T19:52:21Z",
veh1: 5,
veh10: null,
veh2: 5,
veh3: 6,
veh4: null,
veh5: null,
veh6: null,
veh7: null,
veh8: null,
veh9: null,
version: null
}
]
我想得到一个:veh1..:veh10 的数组作为[5, 5, 6, null, ...]。这样做有很多麻烦...
我曾想过在我的助手中使用 JBuilder,但现在我把事情搞砸了......
我怎样才能做一些像使用.only(:veh1..:veh10 这样简单的事情并删除空值......然后我可能会创建一个数组。
想一想,cmets,我是不是很笨?这应该很容易吗?我是这里的初学者。 :)
我的答案
这感觉真的很草率。有一个更好的方法吗??更优雅??
def item_ppu(id)
item = Item.where(:_id => id)
newitem = item.map{|i| [i.veh1, i.veh2, i.veh3, i.veh4, i.veh5, i.veh6, i.veh7, i.veh8, i.veh9, i.veh10]}
h = Hash.new(0)
newitem[0].each { | v | h.store(v, h[v]+1) }
f = 2*h[2]#lots more math
return f
end
【问题讨论】:
-
这是返回内容的 JSON 表示吗? Ruby 中没有
null。实际对象是什么? -
@Zach,是的,这就是 json 输出。我不确定如何检查对象...我的调试方法是更改帮助程序并刷新浏览器...这很糟糕吗?
-
不,不一定,但在测试和使用控制台后,这将是我的第三选择。这是 Mongoid 模型吗?
标签: ruby-on-rails mapping mongoid helpers jbuilder