Question

I have a User model. I want display a dropdown in form_for for selecting a user from User model. I have a method full_name in user that can be used to display full name of user. How would I pass a user collection to this dropdown?

Was it helpful?

Solution

<%= f.collection_select :full_name, User.all.order(:full_name),:id,:full_name, 
                                                           include_blank: true %>

Reference Link : RubyOnRails API

Another way,just consider one example for fixed drop down values ::

Now want to change the :temperature control to a dropdown list, accepting hot, medium and cold as values. Then you can do that this way:

<% form_for @article do |f| %>
  <%= f.text_field :name %>
  <%= f.collection_select :temperature, Article::TEMPERATURES, :to_s, :to_s, 
       :include_blank => true
  %>
  <%= f.submit "Create" %> <% end %>
<% end %>

You will now have to define the Article::TEMPERATURES constant in your Article model. It shouldn't be very difficult:

class Article < Activerecord::Base

  TEMPERATURES = ['hot', 'medium', 'cold']

end

OTHER TIPS

You can use something like this:

<%= f.select :attribute_name, User.all.collect {|p| [ p.full_name, p.id ] } %>

Replace attribute_name with the field name where you would like to store the selected value. The above drop down will have display text as the full_name of user and upon selection of a user, id of that user would be stored in attribute_name.

NOTE: Since, you didn't specify which value you would like to be stored in the database, I used id of the user. If you want to store full_name of selected user then use p.full_name instead of p.id

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top