Rails foundationSort Order

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

Rails.application.routes.draw do  resources :posts do    resources :comments  endend

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.

# app/controllers/comments_controller.rbclass CommentsController < ApplicationController  def create    @post = Post.where(id: params[:post_id]).first    @comment = @post.comments.build(comment_params)        if @comment.save      redirect_to post_path(@post)    else      # error handling    end  end    private    def comment_params    params.require(:comment).permit(:body)  endend

Implementing the Form

# app/views/posts/show.html.erb# ...<%= form_for [@post, @post.comments.build] do |f| %>  <div class='form-group'>    <%= f.text_area :body, class: 'form-control' %>  </div>  <div class='actions'>    <%= f.submit "Save", class: 'btn btn-success' %>  </div><% end %>

We should now be able to see our form in the browser.