Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i have a view in my postgres database that returns an array on my frequencies column. unfortunately, it sometimes returns values like {NULL} (due to the raw data).

in my rails view, i have something like:

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}:

in the javascript console it shows:

Uncaught ReferenceError: nil is not defined 

and in the html it shows:

  ...
  }, {
    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?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Try this:

 <%= i.frequencies.compact %>

compact example:

 [nil].compact #=> []
 [1,2, nil, 3, nil].compact  #=> [1,2,3]
share|improve this answer
    
woohoo! thanks! –  yee379 Mar 27 '13 at 19:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.