A Solution to Our Movie Casting Lecture
Let’s look at an example from yesterday’s lecture where we made a Movie Casting application. Here’s where we left off:
Let’s take a look at the view file in a browser:

Looks good. What do our params look like when we submit this form?
<ActionController::Parameters {"authenticity_token"=>"MBWUpvbTtXnw2rldx8NNpgMEyRdLMKom2VKYowSKE47g3vuDf0RZ0OlXu8YzfYzoWYRgkOdeX056OZ8uJVj5rA==",
"role"=>{"actor_id"=>"3"}, "commit"=>"Cast this movie.", "controller"=>"movies", "action"=>"create_cast", "id"=>"1"} permitted: false>Our “role” param key points to a hash with an “actor_id” key and a value of “3”. Sigourney Weaver has an actor_id of 3 in our database, so it looks like our form_with is only submitting the last collection_select item. But we have a hash! Maybe we can try adding to it?
Since we’re using each_with_index, we have access to an index variable, “i”. On line 6, let’s change “actor_id” to “actor_id[#{i}]”. This will allow us to add to the hash we’re making instead of overwriting it. Let’s try submitting the form again and seeing how the params changed.
<ActionController::Parameters {"authenticity_token"=>"pEUSwgNYDx5yqI7Wjs1gwOobcpjMA3W9FIDZKzZwk9p0jn3nis/jt2sljE16c6GOsJvbH2BtgNW3696mF6J5+A==",
"role"=>{"actor_id"=>{"0"=>"1", "1"=>"2", "2"=>"3"}}, "commit"=>"Cast this movie.", "controller"=>"movies", "action"=>"create_cast", "id"=>"1"} permitted: false>Great! It looks like we added to the hash instead of overwriting it. Let’s see how we can use this hash to cast our movie. To the controller!
On line 10, we establish an array of roles for the movie we’re casting called “movie_roles”. These roles are in the same order as they were shown in the form, something important to note. On line 11, we save the params hash that we set up earlier to an array called “array”. Then, we access each key in that array (which corresponds to each role in the movie) and set each role’s actor_id to that key’s value (which corresponds to the actor_id we submitted in the form). Lastly, we save the updated role in the database and redirect to the movie’s show page.

That’s it!
