Search code examples
ruby-on-railsrubysimple-form

Getting value of an object in collection select


I have created drop down list for employees.

  • What I want?

I want to select full Name for each one of them.

  • Type of form:

I use simple_form. I actually have:

= f.input :person_id, label: "Employee", collection: @employee, prompt: "Select employee"

Result(I know, that is reference):

enter image description here

Before I use collection_select, but simple_form doesn't support validation for this type of collection. Code for collection_select. This type of drop down list displays properly full name.

= f.collection_select :person_id, @employee, :id, :fullName, {prompt: "Wybierz pracownika"}, {class: "form-control"}

Update: fullName is a method in a person.rb model.

 def fullName
   "#{first_name} #{last_name}"
 end

Object employee.

@employee = Person.where.not(type: "Client")

Solution

  • The easiest way to do this is :

    = f.select :person_id, options_for_select(@employees.map{|e| [e.fullName, e.id]}), {:prompt=>"Wybierz pracownika", :required => true}
    

    It will show full names as select options and will dispatch ids as values with form.