Reputation: 24875
Suppose there's a Photos
model. For this model I have several views: recent photos, popular photos, favourite photo etc.. How do I go about creating the controller for this model. There are different options:
One PhotosController
with an index
action. I send a parameter to the index action and based on this parameter the controller makes a query to the DB and returns @photos
to the view. This has the disadvantage that the index
action will become quite big.
Same as above but logic for deciding what query to make is extracted into a service, so that the controller stays lean.
One PhotosController
with several actions recent
, popular
, favorite
etc., but that's not very restful.
Several controllers with index
actions - RecentPhotosController
, PopularPhotosController
etc.. In that case though I must still have a normal PhotosController
to hande show
, edit
actions.
Is there an established best practice for this and what are the considerations when choosing one of those options?
Upvotes: 0
Views: 25
Reputation: 115511
I would go way 1.
The controller should not grow big: you must create the query out of it from params in a service object.
Something like:
def index
@photos = PhotoQuery.new(params).call
#....
end
class PhotoQuery
attr_reader :params
def initialize(params)
@params = params
end
def call
case params[:type]
when 'recent' then Photo.recent
else Photo.all
end
end
end
Upvotes: 2