在before_save Rails之前替换Nil值

时间:2016-12-17 03:55:47

标签: ruby-on-rails json ruby model

我有一个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

有更有效的方法吗?

由于

1 个答案:

答案 0 :(得分:3)

我的建议是将它们作为nil留在数据库中。如果您需要显示"未列出"在您的UI中,然后在显示数据时执行此操作。这提供了许多好处:

  • 您可以轻松更改"未列出"在未来的其他方面。
  • 您可以即时翻译。
  • 你不会混淆一个空白"未列出"合法的"未列出"由用户输入。