Strong parameters and arrays

Let's say we have a typical many-to-many association between two models, post and category. We want inside the form of the post to add a typical multiple option-select html element with all the categories so you can choose which category this specific post will have. So you will write something like the following:
<%= f.collection_select :category_ids, Category.order("name"), :id, :name, {}, {multiple: true} %>

Now you are navigating to the form, you select some categories, push submit and... nothing saved. You check the logs, you forgot to have it on permit-strong parameters. Ok cool, no problem, you are going to the permit, you are adding a symbol :category_ids, try again the same workflow and... again nothing. You are checking the documentation of permit, you see that you have to define it as an array.

Cool, no problem then you are setting this category_ids: [], do the same workflow and after the submit, if you are lucky enough it will work. Why it depends on luck? Because it matters if you have added the category_ids: [] in the end of the permit. If you haven't, then you will probably get an error.

Ok, why is this error appeared? Looking a bit at the strong parameters code, you can see that in line 68 there is an each statement and it is checking if it is an array or symbol/string. If you add the array between symbols, it will throw a syntax error and that's because it messes up the attributes, it doesn't understand where the array category_ids starts and where it stops and you are adding after that another symbol. So you have two solutions, either you have to add brackets, something like {category_ids: []} and put it wherever you want, or you can add it at the end. Check this answer on stackoverflow for some more info (check the comments of the answer).

Max one mail per week.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.