Search code examples
ruby-on-railsarraysformshashcollection-select

Rails collection_select how to reference hash correctly?


As you can see below I have created a hash but I don't know to to reference that hash in my collection_select tag. So I already did this successfully but my hash was a collection of profile objects, when I try to do it with a collection of key value pairs it doesn't seem to work, I'll show you the code that worked correctly first then I'll show you the code that didn't work.

THIS GAVE ME ZERO ERRORS:

  <% listoflos = [] %>
  <% @profiles.each do |profile|  %>
    <% listoflos.push(profile) if profile.title == "loan officer" %>
  <% end %>
  <%= f.collection_select :loanofficer_id, listoflos, :user_id, :firstname, {prompt: true} %>

THIS GIVES ME ERROR:

  <%= f.label "Progress" %>&nbsp
  <% listofprogress = [["1 Not contacted", "1"],["2 Interested", "2"],["3 App Taken", "3"],["4 Priced", "4"],["5 Disclosure Signed", "5"],["6 No Appraisal Needed", "6"],["7 Appraisal Ordered", "7"],["8 Appraisal Recieved", "8"],["9 In Underwriting", "9"],["10 Closing Scheduled", "10"],["11 Closed", "11"],["12 Dead", "12"],["Unknown", "unknown"]] %>

    <%= f.collection_select :progress, listofprogress, :id, :value, {prompt: true} %>

I get an error:

NoMethodError in Records#edit Showing c:/Sites/TeamCRM/app/views/records/_eform.html.erb where line #52 raised:

undefined method `value' for ["1 Not contacted", "1"]:Array

Do you know what I'm doing wrong?


Solution

  • From the Rails docs

    collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

    The :value_method and :text_method parameters are methods to be called on each member of collection.

    Your code is trying to call value on an Array, which doesn't respond to that method.

    Try using options_for_select

    <%= f.label "Progress" %>
    <% listofprogress = [["1 Not contacted", "1"],["2 Interested", "2"],["3 App Taken", "3"],["4 Priced", "4"],["5 Disclosure Signed", "5"],["6 No Appraisal Needed", "6"],["7 Appraisal Ordered", "7"],["8 Appraisal Recieved", "8"],["9 In Underwriting", "9"],["10 Closing Scheduled", "10"],["11 Closed", "11"],["12 Dead", "12"],["Unknown", "unknown"]] %>
    
    <%= f.select :progress, options_for_select(listofprogress, @record.progress_id.to_s), {prompt: true} %>