Skip to content

Instantly share code, notes, and snippets.

@titaniumtails
Forked from harryworld/nested_resources.md
Last active August 29, 2015 14:08
Show Gist options
  • Save titaniumtails/1ad9cf301cde09be2e11 to your computer and use it in GitHub Desktop.
Save titaniumtails/1ad9cf301cde09be2e11 to your computer and use it in GitHub Desktop.

Nested Resources

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

Deep Nesting

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.

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

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