Reputation: 4219
I'm having quite a bit of trouble with assigning has_many: through
in Rails 4.
I have a functioning has_many: through
with the table products
and programs
joined at the table program_products
. My models are functioning correctly, as Product.programs = Program.all
successfully assigns programs
to my products
. However, I cannot figure out how to gain that functionality in the view.
I've read that the most common way is with a collection_check_boxes
, so I devised the following in my form view:
<%= form_for(@product) do |f| %>
<%= f.collection_check_boxes(:programs, Program.all, :id, :name ) %>
<%= f.submit %>
<% end %>
This gives me HTML output of
<input type="checkbox" value="1" name="product[programs][]" id="product_programs_1">
<input type="checkbox" value="2" name="product[programs][]" id="product_programs_2">
and so on.
When I submit my form, I get this response in the params:
{"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"xxx",
"product"=>{"name"=>"Test",
"description"=>"desc test",
"price"=>"10",
"programs"=>["1",
"2",
"3",
""]},
"commit"=>"Update Product",
"id"=>"18"}
With no errors. However, my database never actually updates, so I can't figure out what's going wrong. Here are the important bits of my controllers:
products_controller.rb (main CRUD controller)
def update
@product = Product.find(params[:id])
if @product.update_attributes(product_params)
redirect_to(pages_dashboard_path)
end
end
private
def product_params
params.require(:product).permit(:name, :description, :price, :programs)
end
I can't figure out what's going wrong, since I'm not getting any outright errors. The documentation for collection_check_boxes on Rails is rather confusing, so I suspect that my error may lie in that setup.
Thanks
Upvotes: 0
Views: 84
Reputation: 4147
I think you should use program_ids
instead of programs
in your collection_check_boxes
call. And make sure to change that in the permition method as well.
Upvotes: 1