Prerequisites: Basic understanding of Ruby on Rails, and familiarity with MVC architecture.
Step-by-Step Guide
ruby
# config/routes.rb
Rails.application.routes.draw do
resources :posts do
resources :comments
end
end
ruby
# app/controllers/comments_controller.rb
def index
@post = Post.find(params[:post_id])
@comments = @post.comments
end
Best Practice: Avoid nesting resources more than 1 level deep. Deeply nested resources can lead to complex code that is hard to maintain.
Code Examples
Example 1: Creating a new comment on a post.
ruby
# app/controllers/comments_controller.rb
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
Here, we first find the post using the 'post_id' from the parameters. Then we create a new comment related to that post. Finally, we redirect the user back to the post.
Example 2: Deleting a comment from a post.
ruby
# app/controllers/comments_controller.rb
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
We're finding the post and the comment in the same way as before. But this time, we're calling 'destroy' on the comment and then redirecting the user back to the post.
Summary
Additional resources: Rails Routing guide
Practice Exercises
Remember, practice is key when it comes to mastering new concepts in programming. Happy coding!