【发布时间】:2016-12-17 03:55:47
【问题描述】:
我有一个 json 文件要导入到我的 Rails 数据库中。
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
有没有更有效的方法?
谢谢
【问题讨论】:
标签: ruby-on-rails json ruby model