首页 > 解决方案 > 如何让自定义字符串显示在 form.collection_select 的下拉列表中

问题描述

我正在研究红宝石和轨道。我的用户模型与名字和姓氏一起存储。现在,我想从一个使用集合中搜索,并且搜索是在使用form_for的表单中。我希望下拉字符串显示用户的全名,并按用户全名排序。怎么办?目前,我只知道如何按姓氏排序,并显示姓氏。

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

标签: htmlruby-on-railsrubyform-for

解决方案


将 full_name 实例方法写入用户模型以使用对象访问它。

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

然后你可以使用如下的集合选择 -

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

推荐阅读