Rails复选框为数组

时间:2015-09-04 11:41:09

标签: ruby-on-rails arrays forms checkbox

我正在尝试将多个复选框作为数组传递给db表。 所以我想在项目中添加多个主题。

= form_for @project, url: admin_projects_path, :html => { :multipart => true } do |p|
  %p
    =p.label :name
    =p.text_field :name 
  %p
    = p.label :topic
  %p
    = p.label "Value1"
    = p.check_box(:topic, {:multiple => true}, "value1", nil)
    = p.label "Value2"
    = p.check_box(:topic, {:multiple => true}, "value2", nil)
    = p.label "Value3"
    = p.check_box(:topic, {:multiple => true}, "value3", nil)
  %p
    = p.submit

但是这里的主题在项目中返回nil,即使我检查多个复选框也是如此 (我添加到控制器中的白名单参数中,因此无法成为原因)

我在这里做错了什么?

编辑:

这是控制器的代码:

def new
  @project = Project.new
end

def create
  @project = Project.new(project_params)

  if @project.save
    redirect_to admin_projects_path
  else
    render :new
  end
end

private
# param white listing

def project_params
  params.require(:project).permit(:name, :description, :photo, :project_type, :highlight, :content, :topic, :category)
end

找到解决方案:

查看正确。

 serialize :topic

需要添加到项目模型

并且应该编辑许可证参数,以便它们只接受主题上的数组

private
# param white listing

def project_params
  params[:project][:topic] ||= []
  params.require(:project).permit(:name, :description, :content, topic: [])
end

1 个答案:

答案 0 :(得分:0)

如果在数据库中保存数组,请将其添加到模型中:

class Project < ActiveRecord::Base
  serialize :topic
end

<强>更新

将表格改为:

 %p
   = p.label "Value1"
   = p.check_box(:topic, {:multiple => true}, "value1", nil, name:"project[topic][]")
   = p.label "Value2"
   = p.check_box(:topic, {:multiple => true}, "value2", nil, name:"project[topic][]")
   = p.label "Value3"
   = p.check_box(:topic, {:multiple => true}, "value3", nil, name:"project[topic][]")

如果您获得允许参数问题,请添加如下:

params.permit! #only if you get issue of permitted parameter

希望这会对你有所帮助。