itzmurd4
itzmurd4

Reputation: 663

rails options value to id

I would like to have the option value changed from the users name to the users ID on the option value in html.

For example:

<option value="John">John</option>
<option value="Jim">Jim</option>
<option value="Kelly">Kelly</option>
<option value="Monica">Monica</option>
<option value="Ralp">Ralp</option>

This is what my html is outputting, and i would like the value to be the users id, such as:

<option value="1">John</option>
<option value="2">Jim</option>
<option value="3">Kelly</option>
<option value="4">Monica</option>
<option value="5">Ralp</option>

I would also like it to be dynamic so when more and more users come I do not have to manually enter their names.

My rails for currently looks like this:

<%= form_tag '/login', method: 'post' do %>
    Name:
    <br/>
      <%= select_tag :user_id, options_for_select(@users) %>
    <br/>
    <br/>
    <%= submit_tag 'Login' %>
  <% end %>

And my controller as such:

  def login_user
    user = User.find_by_name(params[:user_id])
    if user
      session[:user_id] = user.id
      redirect_to user_path(user)
      return
    end

    flash[:error] = 'Sorry that user not in the system.'
    redirect_to root_path
  end

Could someone please help point me in the right direction. Thank you in advance.

Upvotes: 0

Views: 34

Answers (2)

usha
usha

Reputation: 29349

I don't understand what you mean by "dynamic". But following should fix your select issue

<%= form_tag '/login', method: 'post' do %>
    Name:
    <br/>
      <%= select_tag :user_id, options_for_select(User.all.collect{|u| [u.name, u.id]}) %>
    <br/>
    <br/>
    <%= submit_tag 'Login' %>
  <% end %>

Upvotes: 1

itzmurd4
itzmurd4

Reputation: 663

Got it, I used this instead:

   <%= collection_select(:user, :id, User.all, :id, :name) %>

this gave me a drop down tab with user value and user name. Thank you all!

Upvotes: 0

Related Questions