Using ROR 2.3.8.
Here’s my code:
class CitiesController < ApplicationController
def show
...
end
def western
@city = City.find(params[:id])
@spots = Spot.paginate(
:conditions => ["(city=? or state=?) and country=? and shop_type=?", "#{@city.name}", "#{@city.name}", @city.country, "Places"],
:page => params[:page],
:per_page => 20,
:order => 'rating_average DESC'
)
end
def middle-east
@city = City.find(params[:id])
@spots = Spot.paginate(
:conditions => ["(city=? or state=?) and country=? and shop_type=?", "#{@city.name}", "#{@city.name}", @city.country, "Food"],
:page => params[:page],
:per_page => 20,
:order => 'rating_average DESC'
)
end
def asian
@city = City.find(params[:id])
@spots = Spot.paginate(
:conditions => ["(city=? or state=?) and country=? and shop_type=?", "#{@city.name}", "#{@city.name}", @city.country, "Accommodation"],
:page => params[:page],
:per_page => 20,
:order => 'rating_average DESC'
)
end
end
I’ve created western.html.erb, middle-east.html.erb, asian.html.erb and _shops.html.erb.
So the first three are basically empty, but yields the _shops.html.erb in order not for me to recode the view layout.
Is there a better method in writing the controller?
Thanks!
The proper way to dry this up in Rails 2.3.X is a named scope in your model. Excessive/repeated querying in your Controller is a hint of a code smell. If you don’t believe me about this, Jamis Buck has got my back! http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model
In your Spot model:
In your Cities Controller:
What this is accomplishing is removing most of the querying logic out of the Controller. This is a good thing, as it allows you to find spots by city and type in other controllers if the need arises. Pagination is likely to be specific to your individual controller, so I tend to exclude it from the scopes inside models. If you want to build an API, you might limit to 50 instead of 20 for example and want to sort by a different method.