基于 table 的下拉菜单和额外的自定义值 Rails

Dropdown based on table with additional custom value, Rails

因此,我可以使用以下内容根据数据库对象

创建一个 select 框
 <%= f.collection_select :role, Role.where(company: current_company), :name, :name %>

我希望能够在其上添加自定义字段,例如 "all" 或 "none" selection,我该怎么做,我必须将临时行添加到活动记录对象?

您可以在 :include_blank 中包含一个空白值作为选项参数。

任何更多的控制,您将需要手动构建 select with select and options_for_select or options_from_collection_for_select 的选项。这听起来可能有点困难,但实际上并没有那么糟糕。

<%= f.select :role, options_for_select([["none", "None"], ["all", "All"]]) +  options_from_collection_for_select(Role.where(company: current_company), :name, :name) %>

这里我们只是连接两个选项标记字符串。