This has been forked from Harry's documentation on Nested Resources.
This is for when you have Associated models. In this case, we have a Post & Comment model. This is how we associate it:
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post #notice this is singular
end
In the terminal, we'll put:
rails g migration AddPostIDToComment post_id:integer
Allows you to create urls that make sense, that are linked to each of the models referenced.
In a very verbose way, it looks like:
http:localhost:3000/comments/new/?=:post_id
# where ? is parameters
http:localhost:3000/comments/new/?=22
So, in the routes.rb
, put this:
resources :posts do
resources :comments
end
Every path looks like /posts/:post_id/comments
, or /posts/:post_id/comments/new
or http:localhost:3000/posts/22/comments/new
, or http:localhost:3000/posts/22/comments/1000/edit
But this is still too long, we may want to use /comments/:comment_id
, thus we want to setup Shallow Nesting.
resources :posts do
resources :comments, only: [:index, :new, :create]
end
resources :comments, only: [:show, :edit, :update, :destroy]
This is very sematically easy to understand. This is very precise, only these views will be included inside. But its quite troublesome, to put everything one by one.
This looks ugly, we can improve it by doing this.
resources :posts do
resources :comments, shallow: true
end
So, the path would be /posts/:post_id/comments
and /comments/:id
You can check using rake:routes
, and use the following to show the path
post_comment_path(@post, @comment)
<%= form_for [@article, @comment] do |f| %>