【问题标题】:Rails save data from checkboxesRails 保存复选框中的数据
【发布时间】:2014-05-19 13:59:24
【问题描述】:

我有以下表格

 <%= simple_form_for(@software)  do |f| %>
 <%= f.input :softwarename, :collection => software_options, as: :check_boxes %>

还有这个助手。

module SoftwareHelper

def software_options
    ['7zip','SysInternals','Office','PDF-Creator']
end
end

我的应用程序控制器如下所示

def software_params
    params.require(:software).permit(:softwarename => [])
end

这是我的软件控制器:

def new
    @software = Software.new
end

def create
    @software = Software.new(software_params)

    @software.save
    redirect_to @software
end

当我尝试将表单输入保存到我的数据库 (sqllite) 时,我收到以下错误:

TypeError: can't cast Array to string

我必须将数组转换为字符串吗?

【问题讨论】:

  • collection 选项将使数据作为数组传入。因此,您需要将此数组转换为您在数据库中存储数据的任何形式,您没有指定。您实际上是如何存储它的?

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


【解决方案1】:

您收到错误

TypeError: can't cast Array to string

因为您尝试保存的属性,即softwarename 在数据库中的类型为String,并且您将其值作为Array 从表单中传递(带有复选框)。

您可以做的是使用serialize方法将softwarename属性标记为序列化,以便将作为softwarename的值传递的数组转换为字符串,然后再将其保存到数据库中。如果您从数据库中检索属性,这还将处理从 StringArray 的反序列化。

class Software < ActiveRecord::Base
  serialize :softwarename, Array  ## Add this line
  ## ...
end

详情请参阅serialize method documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-14
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多