Created
November 15, 2011 06:24
-
-
Save jkongie/1366325 to your computer and use it in GitHub Desktop.
Solution using query string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/routes.rb | |
resources :posts, :only => [:index] | |
# post.rb | |
scope :recommended, where(:recommended => true) # having a guess on your db structure | |
scope :recent, order('created_at DESC').limit(10) | |
scope :popular, where(:like_count => true) # again having a guess | |
# app/controllers/posts_controller.rb | |
before_filter :setup_filter, :only => :index | |
# The long way | |
# You could probably move this logic into a method on the Post model ( maybe Post.filter ) | |
def index | |
if @filter == 'recent' | |
@posts = Post.recent | |
elsif @filter == 'popular' | |
@posts = Post.popular | |
else | |
@posts = Post.recommended # lets make this the default | |
end | |
end | |
# Another more magic way | |
# This technique relies on the scopes being the same name as the filter | |
def index | |
@posts = Post.send(@filter) | |
end | |
private | |
def setup_filter | |
@filter = params[:filter] || 'recommended' | |
end | |
# so people would hit it at | |
# /posts | |
# /posts?filter=recent | |
# /posts?filter=popular | |
# | |
# In your index.html.erb file you will have access to the @filter and @posts variables which you can use to render accordingly. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment