ruby-on-rails - 枚举,如何在 simple_form 中显示多个单词?
问题描述
我正在使用枚举:discount_type
。枚举是percent
或price
。
为清楚起见,我想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
解决方案
从文档:
映射通过具有复数属性名称的类方法公开,该方法在 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 %>
推荐阅读
- r - 为什么 ggpairs 函数中的散点图上没有黄土层?
- javascript - 有没有更好的方法来写“a == b?c:a”?
- php - 如何在 laravel 中使用 Laravel 子查询与 groupby 和 where
- javascript - 我正在寻找一种通过网站、应用程序或程序使用编程来批量发送 WhatsApp 网络消息的方法
- django - Django 代码不适用于以下脚本
- c# - .net Core 2.2 EF:SaveChangesAsync() 将不相关的列设置为 null
- c++ - 如何修复 tromeloeil 中的“RETURN missing for non-void function”错误?
- twitter-bootstrap - 在 Blazor 应用中导航后,引导工具提示仍然可见
- python - 在 Vim 上,运行最简单的 python 代码时出错
- wso2 - wso2 apeman3:配置调用OpenWeather api时APPID放在哪里?