TAGS :Viewed: 13 - Published at: a few seconds ago

[ Rails: Preselect Option from dropdown menu ]

i have a working filter on a table, now i want to preselect one of the filters according to in which team a user is. The code for the filter is the following

<%= form_tag request.path, :method => 'get' do %>  
    <%= select_tag "filter", options_for_select([ "Alle", "Men", "Women", "Juniors" ],  params[:filter]), class: 'my_filter'%>
<% end %>

Now every User belongs to one of the four groups, in the User DB identified as team_id now if i open the page i want to select the according fitler for each user as a default.

Thank you for your help

edit:

working with this js to update the code

<script type="text/javascript">
$(function(){
    $('select.my_filter').on('change', function(){
      alert($(this).val())
    $(this).closest('form').submit()
    })
})

Answer 1


Options for select accepts a selected option:

options_for_select(["Alle", "Men", "Women", "Juniors"], selected: "Men")

See http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_for_select

In general you can use form builders like simple_forms or formtastic that already select the options for you according to the model attributes.