The Gugaru
The Gugaru

Reputation: 648

Ruby On Rails - Forms For Select Dropdown Selected option on Edit

Ok so I am using Rails 5 and the latest stable build of Ruby. What I am attempting to do is have a select box have the correct option selected on the edit view.

This is what I have so far create_users

class CreateUsers < ActiveRecord::Migration[5.0]
   def change
      create_table :users do |t|
         t.string :email
         t.string :password
         t.integer :user_type_id
         t.timestamps
      end
   end
end
class CreateUserTypes < ActiveRecord::Migration[5.0]
   def change
      create_table :user_types do |t|
         t.string :name
         t.text :description
         t.timestamps
      end
   end
end

There are no relationships between these tables, all UserType is just a support table. I can get it to output the drop down and save to the database I just cannot get the darn thing to display the appropriate selected option on edit.

Here is my form code

<%= form_for(user) do |f| %>
      <% if user.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:</h2>

          <ul>
          <% user.errors.full_messages.each do |message| %>
            <li><%= message %></li>
          <% end %>
          </ul>
        </div>
      <% end %>



      <div class="field">
        <%= f.label :email %>
        <%= f.text_field :email %>
      </div>

      <div class="field">
        <%= f.label :password %>
        <%= f.text_field :password %>
      </div>

      <div class="field">
        <%= f.label :user_type_id %>

        <%#= select_tag('user_type', options_for_select(UserType.all.collect {|ut| ut.name ut.id})) %>
        <% user_type_array = UserType.all().map { |type| [type.name, type.id]} %>
        <%= f.select(:user_type_id, options_for_select(user_type_array), :selected => f.object.user_type_id) %>
        <%#= options_from_collection_for_select(UserType.all(), :id, :name) #just outputs text %>
        <%#= f.select_tag('user_type_id', options_from_collection_for_select(UserType.all(), :id, :name)) %>
      </div>
    <%= params.inspect %>
      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>

Upvotes: 0

Views: 2028

Answers (1)

Shannon
Shannon

Reputation: 3018

Use the value in options_for_select, it takes an optional selected parameter:

options_for_select(user_type_array, f.object.user_type_id)

Upvotes: 1

Related Questions