我有一个json文件,我将其导入到我的Rails DB中。
JSON:
{
"data": [{
"title": "foo",
"color": "bar",
"size" : "baz",
"occupation" : "engineer",
"location" : "dallas",
"car" : "tesla",
"married" : true,
"dogs" : 4,
"food" : "tacos"
}]
现在让我们说“标题”没有在其中一个样本中列出,它存储为nil。我知道我可以在模型
中使用before_save更新它Class Person
before_save :replace_nil_values
private
def replace_nil_values
self.title = "Not Listed" if title == nil
end
end
这很有效。问题是如果缺少多个属性或列为nil会发生什么?我觉得这样做会非常低效:
def replace_nil_values
self.title = "Not Listed" if title == nil
self.color= "Not Listed" if color == nil
self.size = "Not Listed" if size == nil
self.occupation = "Not Listed" if occupation == nil
self.location = "Not Listed" if location == nil
self.car = "Not Listed" if car == nil
end
有更有效的方法吗?
由于
答案 0 :(得分:3)
我的建议是将它们作为nil
留在数据库中。如果您需要显示"未列出"在您的UI中,然后在显示数据时执行此操作。这提供了许多好处: