Reputation: 31074
I have an existing search-based app that's being ported to Rails. Due to the legacy nature, I need to preserve existing URLs of the form:
/books # search all books
/books/fiction # search books with :category => fiction
I have these mapped to the index
& show
actions of my controller, and it works fine, but the code and markup for showing all books vs a particular category of books is virtually identical.
What's the best way to combine the show
and index
actions? For this app index
is really a degenerate case of show
with :category => nil
.
I can do:
def index
show
render "show"
end
but that seems kind of ugly. Is there a more idiomatic way to do this in Rails?
Upvotes: 3
Views: 1748
Reputation: 434685
Why not simply use one route with an optional category:
get '/books(/:category)' => 'books#search'
and then in BooksController
:
def search
# Look at params[:category], if it is there then use it
# to search, if it isn't there then list 'em all.
@results = ...
end
Then you have just one route, one controller, one view (to rule them all and in the darkness bind them) and no duplication or chicanery.
Upvotes: 4