I’m on my first Ruby on Rails project and I’m trying to display a list of users in a select box. I want to show all of the users (except the currently logged-in one).
I have that part down right now, using this code in my model, view, and controller:
Request Controller:
def new
@request = Request.new
@users = User.without_user(current_user)
end
New Requests View:
<div class="field">
<%= f.label :user_id, 'Select user' %>
<br />
<%= select_tag(:user_id, options_for_select(@users)) %>
</div>
User Model:
scope :without_user,
lambda{|user| user ? {:conditions =>[":id != ?", user.id]} : {} }
This all works well, but my select box is populated with the object_id of the user. How can I convert that object_id into a first name/last name combination, for example? I tried doing something like:
<%= select_tag(:user_id, options_for_select(@users.first_name)) %>
but that gave me an ‘undefined method error.’ What would be the best way to handle this?
In the select_tag of your view, you can have:
This would display the first_name and when the user selects one of the options, the
user idis what is filled into thevalueattribute for the select tag.If you would like to display the full name, you can have a method in your user model:
And, in your view:
You can find more information about
options_from_collection_for_selecthere