Reputation: 35
I'm trying to pass multiple checkboxes as array to a db table. So i want to add multiple topics to a project.
= 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
but here topic returns nil in the projects, even whenever i check multiple checkboxes (i added to the whitelist params in the controller, so that cant be the cause)
What am i doing wrong here?
EDIT:
This is the code of the controller:
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
Solution found:
View was correctly.
serialize :topic
needed be added to the project model
and the permit params should be edited so they only accept arrays on topic
private
# param white listing
def project_params
params[:project][:topic] ||= []
params.require(:project).permit(:name, :description, :content, topic: [])
end
Upvotes: 0
Views: 2016
Reputation: 1191
If you save array in database add this to your model:
class Project < ActiveRecord::Base
serialize :topic
end
UPDATE
And make your form as:
%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][]")
and if you get permitted parameter issue add like:
params.permit! #only if you get issue of permitted parameter
Hope this will help you.
Upvotes: 2