如何在 rails 中创建仅显示具有特定属性的选项的 collection_select

How to make a collection_select in rails that only displays options with a specific attribute

我正在构建一个应用程序,用户可以在其中自定义 pc(系统)中的组件,基于各自 table 中可用的组件(例如主板 table、cpus table..等)

我希望用户能够通过系统表单中的下拉菜单 select select 组件。

我已经能够通过像这样使用 collection_select 来实现这一点

<%= collection_select(:system, :motherboard_id, Motherboard.all, :id, :model, prompt: true) %>

但是,collection_select 显示了 table 中的所有组件,我希望只显示那些具有 available: true 属性的组件。

我试过了

<%= collection_select(:system, :motherboard_id, Motherboard.any? {|mobo| mobo.available?} , :id, :model, prompt: true) %>

这导致 undefined method 'map' for false:FalseClass screenshot:

我想添加一个 before_save 回调来检查每个项目的可用性,但如果这不是让它工作的唯一方法,我认为就用户体验而言这将是一个糟糕的决定

您可以使用

<%= collection_select(:system, :motherboard_id, Motherboard.where(available: true), :id, :model, prompt: true) %>