Search code examples
arraysruby-on-rails-3mode

Creating an Array with Rails


I am trying to create an array of unique values for future search.

I am using the query BBOrder.uniq.pluck(:trader) --> has 7 values in it and I want to add an 'ALL' option, so the search can return all results.

So I tried two approaches, but they yield almost required results, and I can't combine them without going into some redundant variable creation, so I want to know what the problem is and what causes this behaviour.

1st approach:

@unique_traders = ["ALL"] << BBOrder.uniq.pluck(:trader) #this returns [ALL, and first value of the search]

2nd approach:

@unique_traders = BBOrder.uniq.pluck(:trader) << ["ALL"] #this returns all proper values, but 'ALL' is at the end of list, I want it to be at the top.

Again, I don't want to loop all values and insert one by one, I want to see why this behaviour occurs and how I can fix it.


Solution

  • You need + not << to join arrays.

    @unique_traders = ["ALL"] + BBOrder.uniq.pluck(:trader)
    

    And to answer your usage questions:

    @unique_traders = ["ALL"] << BBOrder.uniq.pluck(:trader) 
    

    This will first create ['All'] as an array, then create an array of BBOrder traders and add the new array as an element to the old array ['All', [array of traders]]