Guys,
I'm working to get my head around REST. Reading the chapter in AWDROR is not helping unfortunately, but I think it may be a result of either an error in my copy of the book, or my understanding in general.
REST in Rails for simple examples is easy to follow, but it's where associations come into the mix that I get a bit confused.
Take the example in the AWDROR book. You have ArticlesController and CommentsController, and the appropriate nested resource mapping to make comments available via articles urls...so that you can do:
/articles/1/comments
and get a list of comments for the article with id 1. So far, so good.
Now, extend this example hypothetically and say that I, for whatever reason, want to get all comments, irregardless of article. One would expect that, if #index is used for all listings of comments, then I'd have to write CommentsController#index as:
def index if params[:article_id] @comments = Article.find(params[:article_id]).comments else @comments = Comment.find(:all) end respond_to do |format| format.html # index.rhtml format.xml { render :xml => @articles.to_xml } end end
This would allow the method to be used in two contexts...one where I'm after /articles/1/comments and one where I'm seeking just /comments
Now, this design could get pretty nasty, I'd presume, because let's say I have other resources in my application that could also have comments. I'm suddenly forced to walk through the parameters for each method that could be called in this way and change the behavior of the resource accordingly.
Here's where I think an error in the book is confusing me. Of course, it may not be an error at all. In the table on page 418, it lists actions that are called in response to various url mappings.
The first listed in CommentsController says that Actions in CommentsController GET /articles/1/comments index comments_url(:article_id => 1)
This says that /articles/1/comments will call #index in the CommentsController, but if you'll note in the actual implementation of the CommentsController, there is no index defined!?!
Which leads me to believe that this is wrong, and that #index will only ever be called when accessed directly via a GET to /comments
So, two questions:
1. Is this actually incorrect on the part of the book? Is #index unnecessary when called in the context of a nested resource? 2. How does one manage a resource controller implemention of a resource that might be shared amongst different parent resources (i.e., I have three resources: Articles, BlogEntries, and ProductListings, all that have a has_many :comments?
Thanks for any help you can provide in cleaning up these mental cobwebs.
John