htmlruby-on-railsrubyform-for

how to let custom string shown in the drop down in form.collection_select


I am working on ruby & rails. My user model is stored with firstname, and lastname. Right now, I want to search from a collection of uses, and the search is in a form using form_for. I would like the drop down string show the user's full name and also ordered by user full name. How to do with that? currently, I only know how to order it by last name, and show last name.

<%= form_for @user do |f| %>
        <%= f.label 'First Choice'%>
        <%= f.collection_select :first, User.order(:lastname), :lastname, :lastname, include_blank: true %>
<%end%>

Solution

  • write a full_name instance method to user model to access it with object.

    class User < ActiveRecord::Base    
      def full_name
        first_name.to_s + last_name.to_s
      end
    end
    

    Then you can use the collection select like below -

    <%= f.collection_select :first, User.order(first_name: :asc, last_name: :asc), :id, :full_name, , include_blank: true %>