简体   繁体   English

postgres阵列和导轨4 erb

[英]postgres array and rails 4 erb

i have a view in my postgres database that returns an array on my frequencies column. 我在postgres数据库中有一个视图,该视图在我的frequencies列上返回一个数组。 unfortunately, it sometimes returns values like {NULL} (due to the raw data). 不幸的是,有时它会返回诸如{NULL}类的{NULL} (由于原始数据)。

in my rails view, i have something like: 在我的Rails视图中,我有类似以下内容:

dataset = [
    <% @item.each do |i| %>
        {   
            name: "<%= i.device %>" 
            lng: <%= i.longitude %> 
            lat: <%= i.latitude %>
            frequencies: <%= i.frequencies.to_s.html_safe %>
        },
    <% end %>
]

which appears to work great - except when it reaches a record that contains {NULL} : 看起来效果很好-除非达到包含{NULL}的记录:

in the javascript console it shows: 在javascript控制台中,它显示:

Uncaught ReferenceError: nil is not defined 

and in the html it shows: 并在html中显示:

  ...
  }, {
    name: "blah",
    lng: -122.2,
    lat: 37.4,
    frequencies: [nil]
  }, { 
  ...

i could fix this by iterating through the list in the controller, but i think this would be rather long winded (and a waste of cycles). 我可以通过遍历控制器中的列表来解决此问题,但是我认为这会花费很长的时间(并且浪费周期)。

is there a way i can get the erb to output the 'correct' [] in (instead of [nil] ) json when it's null? 有没有办法让erb在null时(而不是[nil] )在json中输出“正确” []

Try this: 尝试这个:

 <%= i.frequencies.compact %>

compact example: 紧凑的例子:

 [nil].compact #=> []
 [1,2, nil, 3, nil].compact  #=> [1,2,3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM