collection_select with form_for/form_with
collection_select is a ruby on rails form helper method that is used in place writing a form out in html. On the user side it looks like a drop down menu where the user makes a selection. Through my searches I couldn’t quite find a plain explanation for collection_select and what arguments you need to give to it, so here I will attempt to explain it as simply as I can.
In the picture below is a basic form to create a new song that has the attributes: name, artist, and genre. When a user creates a new song I want them to be able to select from pre existing artists and genres. I already have @artists and @genres set equal to Artist.all and Genre.all in my SongsController.
OK so what are the arguments you need for a collection_select method? They go in this order:
- The first argument you need to give the collection_select is what you want the key to be inside of your params hash and in my example I am wanting the artist id to be the key(:artist_id). You want to name this what the column is called inside of your database.
- The second argument you need to give it is an array of objects to iterate through(@artists or Artist.all could have worked as well).
- The third argument you need is what you want to get from that object so in my case it was the id of the artist(:id)
- The last argument you need is what you want the user to see when they are looking through the drop down menu. I wanted the user to be able to see the name of the artist(:name)
When not using collection_select within a form helper method there is an argument that must come before the ones I listed above and that is an object argument. Since I was working inside of a form that didn’t need to be included because rails already knew my object was a song.
Also when you are getting the data from the form it will be a nested hash so you will need to employ either a strong_params method or require then permit the data that you want to use.
Here is a link to more on strong_params: https://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html