Reputation: 1096
I have a form with nested attributes. My nested attributes all work fine.
But, i want to have a selection of those attributes available for the user to check (true/false) to include in the creation of the form. The below code isn't working for me, unsure of what i'm missing.
Form
<%= form_with(model: staff, local: true) do |f| %>
<%= f.collection_select :user_id, User.order('last_name'), :id, :full_name %>
<%= f.collection_select :department_id, Department.all, :id, :name %>
<%= f.check_box :sale_checkbox, {}, true, false %><%= f.label "Sales" %><br />
<%= f.check_box :management_checkbox, {}, true, false %><%= f.label "Management" %><br />
<%= f.check_box :summary_checkbox, {}, true, false %><%= f.label "Summary" %>
<% end %>
So with the above code, sometimes sales isn't applicable, so a user would deselect it and therefore it wouldn't be included in the form creation.
Controller
def create
@staff = Staff.new(staff_params)
if params[:staff][:sale_checkbox] == true
@staff.sales.build
end
if params[:staff][:management_checkbox] == true
@staff.managements.build
end
if params[:staff][:summary_checkbox] == true
@staff.summaries.build
end
end
def staff_params
params.require(:staff).permit(:sale_checkbox, :management_checkbox, :summary_checkbox)
end
Model
class Staff < ApplicationRecord
attr_accessor :sale_checkbox
attr_accessor :management_checkbox
attr_accessor :summary_checkbox
end
Upvotes: 0
Views: 27
Reputation: 33552
When you look at the server log, you will see that the params
appear under staff
hash, so your code doesn't work. Moreover you should change true
to "true"
and build
to create
. The below code should work
def create
@staff = Staff.new(staff_params)
if params[:staff][:sale_checkbox] == "true"
@staff.sales.create
end
if params[:staff][:management_checkbox] == "true"
@staff.managements.create
end
if params[:staff][:summary_checkbox] == "true"
@staff.summaries.create
end
end
Upvotes: 1