Nested forms in Rails
1) Route: add nested resource to the routes.rb file in the Config folder.
In our example, User will be the parent and WallPost will be the child.
2) Models: Specify relationship between parent and child
- Establish that the User parent has_many children
- Establish that the WallPost child belongs_to the parent
- Important: Don’t forget to specify in the User model that the parent accepts nested attributes for the children (accepts_nested_attributes_for). This will allow the reception of attributes for new instances of the kid in the submission forms.
This association will allow you to access the child’s information in the console through the parent. In our example, we can first find one of our users and then access their wall posts through it by calling .wall_posts:
3) Controller: Add method for permitted params
4) View: create submission form
Make sure to specify to the parent and the child in an array after form_for (remember to leave a space between them, otherwise Rails will not understand what it is)