Skip to content

Instantly share code, notes, and snippets.

@jmccartie
Last active December 21, 2015 04:49
Show Gist options
  • Save jmccartie/6252440 to your computer and use it in GitHub Desktop.
Save jmccartie/6252440 to your computer and use it in GitHub Desktop.
# How to refactor?
def index
@records = Record.includes(:category, :campus, :event).order("records.id ASC").page(params[:page]).per(params[:per_page])
@records = @records.where(params.slice(:campus_id, :event_id, :category_id, :week_reference))
@records = @records.where("service_date_time >= ?", params[:start_time]) if params[:start_time]
@records = @records.where("service_date_time <= ?", params[:end_time]) if params[:end_time]
@records = @records.where("week_reference >= ?", params[:start_week]) if params[:start_week]
@records = @records.where("week_reference <= ?", params[:end_week]) if params[:end_week]
end
@jmccartie
Copy link
Author

Thanks, @nz

I just wrote something very similar. To reduce all the ternary's, I'm calling this first:

  def self.scope_if_value(scope, value)
    return value.present? ? Record.send(scope, value) : scoped
  end

+1 on filter_by_params -- gonna use that to slim down the controller.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment