0

I have a select box in rails. When editing the records, I want the previously selcted items to be highlighted.

I have

    <div class="field">
    <td><%= f.label :keywords %>(Use Control-Click to select multiple keywords)</td>
    <td>  <%= f.select :keywords,
                       options_for_select(@keywords,
                       :selected => @keywords),
                       {:include_blank => false},
                       {:multiple => true, :size =>10}  %>

    </div>

I tried a couple of variations on the :selected => statement above but can't get what I want.

What I'm looking for is When a user edits a record, the f.select will have the selections that are in the database pre selected.

I do see a "Gotcha" here in that even if the items are pre selected, if the user clicks on any item without a Control-click, then the pre selected items are lost.

-------- update-----------

form for

    <%= form_for @bedsheet_line, :html => 
{ :class => 'form-horizontal', multipart: true} do |f| %>
Chris Mendla
  • 987
  • 2
  • 10
  • 25

1 Answers1

0

I got this working.

I changed the form dropdown element to

<%= f.select :keywords,
                               options_for_select(@keywords,
                               :selected =>     previous_keywords),
                               {:include_blank => false},
                               {:multiple => true, :size =>11}  %>

The difference is that the selected => is calling a def called previous_keywords.

previous_keywords is in my controller and looks like

# ---------------------------------------- previous keywords ---------------------------------------------- # This is designed to grab the keywords already entered for a bedsheet. This is so that if a bedsheet records is # edited, then the keywords will be selected if the record is edited. # # NOTE - the eval function is risky. However, since this is an internal application and the input is coming from # a select box, then the risk should be acceptable.

 helper_method :previous_keywords

  def previous_keywords



   @current_bedsheet_line = BedsheetLine.find(params[:id])           # grab the current bedsheet line
    @previous_keywords = @current_bedsheet_line.keywords              # get the keywords for the current bedsheet line

    keywords = Array.new

    keywords  = eval(@previous_keywords)                              # NOTE - the eval function is risky if there is any outside traffic.

   return keywords
  end

NOTE - the eval function is risky. HOWEVER this application is for internal use only, does not deal with financial or other sensitive data and what is being fed to eval is from the database which comes from a drop down list. Therefore the risk should be mitigated.

Chris Mendla
  • 987
  • 2
  • 10
  • 25