html - 如何让自定义字符串显示在 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%>
解决方案
将 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 %>
推荐阅读
- php - 在 PHP regex 中提取数据使用字符串的十进制数和字符(使用单位)
- javascript - 克隆和初始化 jQuery 范围滑块不起作用
- python - 打印不带括号的numpy数组
- javascript - 按钮 onclick 事件虽然调用了函数,但不会重定向到另一个页面
- php - 我如何创建一个实用函数来检查来自 CSV 的空值并替换为打印 NULL
- python - 将 NumPy 图像发送到通道而不使用 discord.py 保存
- c# - 如何检测 UWP 中的“OutOfMemory”或 ios 中“didRecieveMemoryWarning”的 UWP 等效项
- amazon-web-services - 我们可以有多个 cloudformation.template 依赖于一个模板吗
- c# - 无法使用带有承载令牌 .net 核心 MVC 的 api 对 Azure 广告用户进行身份验证
- ios - 如何在我的应用程序的 iPhone 存储中的应用程序设置页面中添加项目