帮助器中的Rails格式对象

时间:2014-02-26 22:43:19

标签: ruby-on-rails mapping mongoid helpers jbuilder

当我在Item.where(:id => id)课程中运行ItemHelper的简单查询时,它会返回

[
{
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一样简单的事情并删除空值...然后我可能会创建一个数组。

思考,评论,我是笨蛋吗?这应该容易吗?我是初学者。 :)

我的回答

这感觉真的很草率。有一个更好的方法吗??更优雅?

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

1 个答案:

答案 0 :(得分:1)

如果这是一个Mongoid模型,并且您只需要查找单个对象,则可以使用find然后映射到您需要的属性:

object = Item.find(id)

您可以使用values_at从对象的属性哈希中检索特定值(在Mongoid中,哈希的键是字符串):

keys = (1..10).map {|n| "veh#{n}" } #=> ["veh1", "veh2" ...
values = object.attributes.values_at(*keys)
values.compact # removes the nil values from the array

一起采取:

object.attributes.values_at(*(1..10).map {|n| "veh#{n}" }).compact

修改

为了编写干净,易懂的代码,以下是我在生产应用程序中实际编写代码的方法:

class Item
  # whatever goes here

  def ppu
    veh_values.inject {|result, value| # ... some calculation }
  end

  private

  def veh_values
    attributes.values_at(*veh_keys).compact
  end

  def veh_keys
    (1..10).map {|n| "veh#{n}" }
  end
end

现在这是Item类的实例方法,所以要调用它,你的语法是:

item.ppu