kakubei
kakubei

Reputation: 5400

Rails (ruby) create empty array when no association found

So I have this bit of code:

= f.input :aspectRatioId, :label => 'Aspect Ratio', 
:input_html => { :id => 'dvd_aspectRatio_tokens', :data => { :load => [@dvd.aspectRatio] } }

I'd like to create an empty array when nothing is found in the association. Right now when nothing is found it returns [null] which trips up tokeninoput javascript that expects []

I can do this by creating another method like this:

def self.series_without_empty_values(dvd)
  series = [dvd.dvd_series]
  if series[0].nil?
    series = []
  end
  return series
end

But I would rather do it in the :load => call on the form. Is this even possible?

Upvotes: 0

Views: 4465

Answers (1)

Casper
Casper

Reputation: 34318

Use Array.compact to remove nil values in an array:

[ "a", nil, "b", nil, "c", nil ].compact
=> [ "a", "b", "c" ]

[nil].compact
=> []

Upvotes: 4

Related Questions