Reputation: 20016
If my model has the following fields:
class Book < ActiveRecord::Base
attr_accessible :author, :title, :year, :month
scope :recent, order('year desc, month desc').limit(3)
end
if I also want to view this data by year, is it better to create a new controller and view for year? Or should I do this using routes?
Upvotes: 0
Views: 69
Reputation: 13014
I would suggest doing this by routes too, but despite of that, you don't need multiple controllers or views as you raised in your concern.
You can do this, by creating a collection route for Book
in routes.rb
as:
resources :books do
get '/by/:timeline', to: 'books#timeline', as: 'timeline', on: :collection
end
This will provide you a GET timeline_books_path
, which can be configured in BooksController
's timeline
method.
Call like timeline_books_path('months')
will make available the URI: /books/by/months
and params[:timeline]
will be equal to 'month' for your disposal at timeline
method.
Similar is the case with timeline_books_path('year')
=> /books/by/year
.
Hope it helps. :)
Upvotes: 1
Reputation: 18530
No, you should reuse the current view and controller. Easiest way would be to add a parameter to the index
action:
class BooksController < ApplicationController
def index
if params[:year]
@books = Book.where(:year => params[:year])
else
@books = Book.scoped
end
end
end
Also, it might be a good idea to move this filter to the Book
model. If you find yourself adding a lot of filters to this action, you can refactor the filtering logic to another class.
Upvotes: 0
Reputation: 24815
I think by routes or query strings would be better, instead of several actions. Just send the response from one action according to different routes or params.
SO does the same(by route):
https://stackexchange.com/leagues/1/month/stackoverflow/
https://stackexchange.com/leagues/1/year/stackoverflow
Upvotes: 0