例如,我需要创建一个带有“Sedentary”,“Lightly Active”,“Active”,“Very Active”选项的下拉列表,并将这些选项作为整数(0,1,... 3)分配给用户。我怎样才能制作哈希
activity_level = {"Sedentary" => 0,
..............,
"Very Active" => 3}
并存储整数值而不是字符串?
答案 0 :(得分:0)
试试这个
f.input :fieldname, as: select, collection: activity_level.keys
保存时
your_model_object.attribute = activity_level[params[:selected_value]]
your_model_object.save
答案 1 :(得分:0)
最佳选择IMO将使用Rails枚举功能,该功能将整数映射到字符串值:
class Activity < AR::Base
enum :activity_level => [ :sedentary, :lightly_active, :active, :very_active ]
def self.activity_levels # or store in an I18n.
{ "sedentary" => "Sedentary", "lighty_active" => "Lightly Active", ...}
end
AR会在内部将这些列存储为整数,但您永远不会处理此问题。您还可以使用方便的查询方法,例如Activity.sedentary.where...
或if @activity.sedentary?
表格(当我没记错的时候,收藏需要成对[v,k]而不是[k,v],所以&#34;轻度活跃&#34; =&gt;&#34;轻微_活动&# 34):
= f.input :activity_level, as: :select, collection: Activity.activity_levels.map(&:reverse)