This Nested resource CRUD tutorial does a great job of quickly explaining how to get a nested resource working in a RESTful Rails application. If you want some more detail, this RESTful Rails Development PDF covers more while still remaining succinct. It is worth a read, even for non-rails developers, since it explains more about how REST works. Especially helpful is the explanation of how the HTTP verbs are used to call different actions in the controller.

Learn from my mistake and don’t forget to modify the nested controller’s create action. This is noted in the PDF but not the post. Left unmodified, the create action will insert the nested records (in this case, “comments”) with NULL foreign keys in the database.

There are a couple ways to fix this. I’ll keep with the posts/comments example in the code snippets below. The method used in the PDF simply adds one line of code to explicitly set the parent id as shown in bold below:

def create
	@comment = Comment.new(params[:comment])
	@comment.post_id = @post.id
	. . . .
end

The other way, which I prefer, is to replace the call to the comment’s new method with a call to the build method as shown in the following code:

def create
	@comment = @post.comments.build(params[:comment])
	. . . .
end

This accomplishes the same thing in one line rather than two, therefore, I like it. Thanks to Ryan for pointing this out on railsforum.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.