Rails: Nested Resources
In this episode we show you how nested resources work. We talk about nested routing and how that translate over to scoping inside the controller. We need to do this to make sure we're working with the right set of objects and that objects we create have the correct parent-child relationship.
Modifying the Routes
resources :posts do
To see what changes were made to our routes we can type rake routes or rails routes
Generating the Comments Controller
To generate our comment we can use rails g controller comments in the command line.
Let's start by filling out our create action.
class CommentsController < ApplicationController
@post = Post.where(id: params[:post_id]).first
@comment = @post.comments.build(comment_params)
# error handling
Implementing the Form
<%= form_for [@post, @post.comments.build] do |f| %>
<%= f.text_area :body, class: 'form-control' %>
<%= f.submit "Save", class: 'btn btn-success' %>
<% end %>
We should now be able to see our form in the browser.