Skip to content

Instantly share code, notes, and snippets.

@harryworld
Last active August 29, 2015 14:08
Show Gist options
  • Save harryworld/6d84d3d2ca93b7c60a4c to your computer and use it in GitHub Desktop.
Save harryworld/6d84d3d2ca93b7c60a4c to your computer and use it in GitHub Desktop.
Nested Resources

Nested Resources

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

Deep Nesting

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.

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

Path for the resource

You can check using rake:routes, and use the following to show the path

post_comment_path(@post, @comment)

form_for settings

<%= form_for [@article, @comment] do |f| %>

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment