【问题标题】:Rails simple_form check_boxes save multiple selections to databaseRails simple_form check_boxes 将多个选择保存到数据库
【发布时间】:2016-04-28 05:04:42
【问题描述】:

我正在尝试列出具有多项选择的复选框。我在模型中有这个数组。

QOL = ["your health", 
    "your stress levels",
    "how safe you feel",        
    "your education",
    "your home"
]

我正在尝试在我的 simple_form 表单中做类似的事情。

<%= f.input :qolselections, as: :check_boxes, :collection => Goal::QOL %>

如何将选择保存到数据库中并能够将它们作为选定的字符串值检索?

【问题讨论】:

  • 您的表单使用什么库,它们看起来像:formtastic 或 simple_form?
  • @Leito 我正在使用 simple_form(我错过了标题中的“m”)

标签: ruby-on-rails ruby-on-rails-4 simple-form


【解决方案1】:

你应该考虑一个枚举,而不是一个常量:

class YourModel < ActiveRecord::Base
  enum qol_selection: ["your health", "your stress levels", "how safe you feel", "your education", "your home"]
end

然后,您的解决方案将类似于以下问题 Saving enum from select in Rails 4.1 (https://stackoverflow.com/a/23686698/637094) 中描述的解决方案:

f.input :qol_selection, :as => :select, :collection => YourModel.qol_selections.keys.to_a

【讨论】:

  • 谢谢@Leito。我真正感兴趣的是能够存储多个选择。就像同时来自枚举的两个值一样。我在您链接的帖子中错过了这个吗?
  • 不,我丢球了。该解决方案将无济于事。对于那个很抱歉。快速思考:您可以将响应序列化以将转换和数组转换为单个字符串?
猜你喜欢
  • 2018-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 1970-01-01
  • 2016-04-08
相关资源
最近更新 更多