class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
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
This is 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 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| %>