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
params[:project][:topic] = ["value1", "value2", "value3"]. Can you please make an edit to your question and add what is actually coming through in params when you check all the checkboxes and submit the form? Also, add to your question the controller code which uses those params. It's possible that your view code is not the problem.