Reputation: 1444
Let's say I have a routes file like this:
resources :books do
resources :authors
end
So if I want to display the authors of a particular book, that's easy:
/books/1/authors
But what if I wanted to display the authors of all the books? I want something like this:
/books/all/authors
or:
/books/authors
Canonically, I assume it's just /authors
but I'm curious if there's another way that's considered standard practice.
EDIT
To clarify, I want routes that look roughly like this:
/books/1/authors
/books/all/authors
So that the route doesn't look dramatically different for when I'm looking at authors for book 1 vs. all book authors, and I want to differentiate displaying authors outside of the context of books vs. with the context of books. So, simply having a resources :authors
and a AuthorsController#index
does not solve my question.
(Let's assume I don't want to have a /views/authors/index.html
file)
Upvotes: 2
Views: 52
Reputation: 371
If you want to have something like /authors
Then apart from your existing routes you can have a separate setup
resources :books do
resources :authors
end
resources :authors
def index
@authors = Author.all # or Author.where(<CONDITIONS for search sort>)
end
And you can add respective views. This will give you good control.
Further to follow DRY principle, you can create a partial as authors/_index.html.haml
(or .erb) and reuse same for /books/1/authors
i.e. authors of a particular book.
Edits: If you do not want a separate controller, then you can distinguish on id param while finding authors collection.
# books/authors_controller.rb
def index
@authors = params[:id] == 'all' ? Author.all : Book.find(params[:id]).authors
end
Upvotes: 1
Reputation: 95
In that case inside the index method of authors add this code @authors = Author.all
As simple as it is
Upvotes: 0