如何编写代码以不包含空值字段到mongodb中


class State
  include Mongoid::Document
  embeds_many :cities
  field :name
end
class City
  include Mongoid::Document
  embedded_in :state
  field :name
  field :population
  field ...
end

我不想将零值的字段包含在 mongodb 中,

nsw = State.new name: 'NSW'
if number_of_people
  nsw.cities.create name: 'Syndey', population: number_of_people
else
  nsw.cities.create name: 'Syndey'
end

因此,有必要检查该字段是否为空或为空。但问题是,当 City 中有很多字段时,代码看起来很丑陋。

如何改进这一点并编写智能代码?

您需要

在模型中定义自定义类方法City如下所示:

def self.create_persistences(fields = {})
  attributes = {}
  fields.each do |key, value|
    attributes[key] = value if value
  end
  create attributes
end

在您的控制器中,无条件地调用此方法:

nsw.cities.create_persistences name: 'Syndey', population: number_of_people

注意:您还可以覆盖模型上create方法而不是定义新方法,但在我看来,我不喜欢覆盖您可能在代码其他部分使用的内容。

现在我们知道你在做什么,你的答案似乎很清楚。但我认为您的问题需要编辑才能告知。

因此,您拥有的是来自用于填充新模型的某个源的数据。因此,在某个阶段,您将拥有一个哈希值,或者至少以某种形式构建哈希值,无论您的数据是如何组织的。采用以下[简称,但相同]:

info = { name: "Sydney", population: 100 }
City.new( info );
info = { name: "Melbourne", population: 80, info: "fun" }
City.new( info )
info = { name: "Adelaide" }
City.new( info )

所以(至少在我的测试中),你将得到每个文档,每次只创建指定的字段。

因此,动态使用哈希(希望您甚至只是以这种方式阅读)将比在代码中测试每个值要聪明得多。

如果你必须做大量的价值测试来"建立"一个哈希,那么你就会遇到这里没有人可以解决的问题。但是构建哈希应该很容易。

最新更新