首页 > 解决方案 > 枚举,如何在 simple_form 中显示多个单词?

问题描述

我正在使用枚举:discount_type。枚举是percentprice

为清楚起见,我想price per day在我的 simple_form 中显示 enum price。我怎样才能做到这一点?

代码

模型

enum discount_type: { percent: 1, price: 0 }

形式

<%= f.input :discount_type, collection: ['percent', 'price'] %>

先前的尝试

model
enum discount_type: { percent: 1, price_per_day: 0 }

form
<%= f.input :discount_type, collection: ['percent', 'price per day'] %>

error message:
==> 'price per day' is not a valid discount_type

标签: ruby-on-railsenumssimple-form

解决方案


从文档:

映射通过具有复数属性名称的类方法公开,该方法在 HashWithIndifferentAccess 中返回映射...

这有点难看,因为per day除了price

Model.discount_types.transform_keys { |key| key == 'price' ? 'price per day' : key }.keys
# ["percent", "price per day"]

因此,以您的形式:

<%= f.input :discount_type, collection: Model.discount_types.transform_keys { |key| key == 'price' ? 'price per day' : key }.keys %>

推荐阅读