Rails 4-简单表单如何保存键和显示值 [英] Rails 4 -Simple Form how to save key and display value
问题描述
我正在尝试在Rails 4中制作一个应用程序.我对表单使用简单的表单.
I'm trying to make an app in Rails 4. I use simple form for forms.
我的模型中有一个名为"self_governance"的属性.
I have an attribute called 'self_governance' in my model.
我已经编写了一个辅助方法,以便可以定义5个级别,可以为该属性存储这些级别,但是这些级别将作为选项显示给用户(而不是数字1 .. 5).
I've written a helper method so that I can define 5 levels which can be stored for this attribute, but which are displayed to the user as options (rather than numbers 1 .. 5).
在我的助手中,我有:
module PreferencesHelper
def self_gov_selector
[
[ 'tier 1','1'],
[ 'tier 2','2'],
[ 'tier 3','3'],
[ 'tier 4','4'],
[ 'tier 5','5'],
]
end
在我的表格中,我有:
<%= f.input :self_governance, :label => "Select your tier", collection: self_gov_selector %>
然后在我的节目中,我试图弄清楚如何显示第1层"而不是"1".
Then in my show, I'm trying to figure out how to display 'tier 1' instead of '1'.
我尝试过:
<%= @preference.self_governance %>
<%= @preference.self_gov_selector %>
我找不到任何有效的方法.它们在视图中都显示1而不是Tier 1.
I can't find anything that works. They all display 1 instead of Tier 1 in the views.
我该如何进行这项工作?
How can I make this work?
推荐答案
由表单发布的params
仅在数组中包含第二个值,因此您很可能将值存储为数据库表中的整数
The params
posted by the form will only include the second value in the array, so you're likely storing your value as an integer in your database table.
一个简单的解决方案是使用enum
将要存储的整数映射到它们表示的值:
A simple solution is to use an enum
to map the integers you're storing to the values they represent:
在您的首选项模型中:
enum self_governance: {
tier_1: 1,
tier_2: 2,
tier_3: 3,
tier_4: 4,
tier_5: 5
}
然后相应地更新您的视图:
<%= @preference.self_governance.try(:humanize) %>
此方法的另一个好处是,您可以通过直接调用枚举来替换您的辅助方法:
An additional bonus of this approach is that you can replace your helper method with calling the enum directly:
f.input :self_governance, as: :select, label: "your label", collection: Preference.self_governances.map { |key, val| [key.humanize, val] }
这篇关于Rails 4-简单表单如何保存键和显示值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!