HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Rails controller method that conditionally filters results

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
conditionallymethodcontrollerrailsthatfiltersresults

Problem

This code for my blog checks to see if tags are in the params hash. If they are, then only posts that are tagged will be paginated. Otherwise, all of the posts are paginated.

class PostsController < ApplicationController
  def index
    if params[:tag]
      @posts = Post.tagged_with(params[:tag]).paginate(page: params[:page])
    else
      @posts = Post.all.paginate(page: params[:page])
    end
  end
end


I feel like this checking of params shouldn't be the concern of the controller, but of some other model like PostParameterChecker. How do you feel about this? Where does this code actually belong?

Solution

Creating a model just to check the parameters is overkill and not idiomatic in Rails. If you need some extra logic, use the existing model. In this case, I'd make Post#tagged_with accept a nil value which wouldn't filter anything:

def Post
  scope :tagged_with, ->(tag) { tag ?  : all }
end

class PostsController < ApplicationController
  def index
    @posts = Post.tagged_with(params[:tag]).paginate(page: params[:page])
  end
end

Code Snippets

def Post
  scope :tagged_with, ->(tag) { tag ? <code to filter> : all }
end

class PostsController < ApplicationController
  def index
    @posts = Post.tagged_with(params[:tag]).paginate(page: params[:page])
  end
end

Context

StackExchange Code Review Q#62856, answer score: 9

Revisions (0)

No revisions yet.