获取集合中对象的值选择

时间:2016-03-24 08:36:26

标签: ruby-on-rails ruby simple-form

我为员工创建了下拉列表。

  • 我想要什么?

我想为每一个选择完整的名称。

  • 表格类型:

我使用simple_form。 我实际上有:

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

结果(我知道,这是参考):

enter image description here

在我使用collection_select之前,但simple_form不支持​​对此类集合进行验证。 collection_select的代码。此类下拉列表会正确显示全名。

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

更新: fullName是person.rb模型中的方法。

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

对象员工。

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

2 个答案:

答案 0 :(得分:1)

您遵循以下代码:

<%= f.collection_select(:person_id, Model.all, :person_id, :fullName,{:prompt=>"Wybierz pracownika"}, {:class => 'form-control'})  %>

您将替换model_name。

或者

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

我认为会帮助你

答案 1 :(得分:1)

最简单的方法是:

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

它会将全名显示为选择选项,并将id作为值发送给表单。

相关问题