Adam
Adam

Reputation: 1285

Ruby on Rails - user forms reference param other than ID

I created the user table and I created a scaffold from there. the user table only has 1 attribute name. I created 1 user called "John"

I then created another scaffold called order generation which references the user (i.e the user must exist before i can order)

  <div class="field">
    <%= form.label :user_id %>
    <%= form.text_field :user_id %>
  </div>

However what I want is to reference the username john and then map back to the user_id. Is there a way to do this using a drop down list and display the username and in the backend, it will pass the user ID ?

update: I tried to do this but it doesnt seem to work also

  <div class="field">
    <%= form.label :user_id %>  
    <%= form.select :user_id, options_for_select(@users.each { |c| [c.name, c.id] })%>
  </div>

Upvotes: 1

Views: 45

Answers (1)

jamesc
jamesc

Reputation: 12837

You need

<%= form.select :user_id, options_for_select(User.all.map{|u|[u.name, u.id]}) %>

Also as pointed out in the comments by @eyeslandic this will also work

options_for_select(User.pluck(:name, :id))

Which I think is actually nicer syntax

Upvotes: 4

Related Questions