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
我不希望将包含nil值的字段包含到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中有很多字段时,代码看起来很难看。
如何改进并编写智能代码?
答案 0 :(得分:1)
现在我们知道你在做什么你的答案似乎很清楚。但我认为您的问题需要编辑才能通知。
所以你拥有的是来自某些来源的数据,用于填充你的新模型。所以在某个阶段你 会有哈希或者至少某种方式以某种形式构建哈希然而你的数据是举办。采取以下[简短形式,但同样的事情]:
info = { name: "Sydney", population: 100 }
City.new( info );
info = { name: "Melbourne", population: 80, info: "fun" }
City.new( info )
info = { name: "Adelaide" }
City.new( info )
所以(至少在我的测试中),你将获得每个文档,每次只创建指定的字段。
因此动态使用哈希(希望你甚至只是以这种方式阅读)比测试代码中的每个值要聪明得多。
如果你必须进行大量的价值测试甚至“建立”一个哈希那么你就会遇到这里没有人可以解决的问题。但建立哈希应该很容易。
答案 1 :(得分:1)
您需要在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
方法,而不是定义新方法,但在我看来,我不想覆盖您可能在代码的其他部分使用的内容。