Basic Rails Nested Forms
On this tutorial-like post we will be building a very basic nested form with rails. The following tutorial was written in order to help beginner Rails developers, understand where the connections need to be made and to know which Active Record keywords or methods we can use for our app to have this necessary functionality.
We will be working with two models: Artist and Song.
Our model Artist will look like this
Our model Song will look like this
Now that our models are set up, we will continue onto building the nested form for our class Artist. which will allow us to create some songs when creating a new artist.
1.- Allow our Artist model to accept attributes from the class Song
- Will allow the parent, in this case Artist to save attributes from the child in this case Song.
- Creates a writer method for us, that is named after the association, which means that the following method will be added to our model
- song_attributes=(attributes)
2.- Building a basic form
form_for
Let’s start our form with a form_for and do not forget to instantiate the artist on the artist#new controller action.
3.- Add a new field on our form, that will turn it into a nested one
artist.fields_for
We added a new song field for our artist form called fields_for and designated that for :songs, then we added a label and text_field for the song name.
4.- Instantiate a new song for our artist in the controller
Just how we created an empty new Artist on our #new controller action, we will create a new song for that artist with the following line.
@artist.songs.build
5.- Update our strong params and add the songs_attributes:
songs_attributes:
Now our artist_params will be able to accept songs, and our create method will look like this:
Great job on finishing your first basic nested form on Rails. I really hope this will help you.