Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails auto convert query string params to integers

I'm trying to implement a form of pagination using limit and offset query parameters. Is there a way to make sure the values are integers otherwise throw a 400 error, perhaps by using strong_parameters? It seems like the sort of thing that would be built in to rails, but I can't find anything.

I could just manually convert the query parameters, but I'd rather use something a bit more bullet proof if possible.

like image 268
Tom Brunoli Avatar asked Dec 03 '13 04:12

Tom Brunoli


2 Answers

Like the commenter @Litmus above, I would recommend using a Ruby gem such as kaminari to manage pagination.

But if you're set on rolling your own, and you're concerned about input sanitization, the simplest method to ensure the "offset" and "limit" parameters are integers might be a filter in your controller:

class YourController < ApplicationController

  before_filter :sanitize_page_params

  # ... other controller methods ...

  private

  def sanitize_page_params
    params[:offset] = params[:offset].to_i
    params[:limit] = params[:limit].to_i
  end

  # ... etc. ...

end

Note that strings such as "foo" will be converted to 0.

like image 125
GladstoneKeep Avatar answered Sep 20 '22 13:09

GladstoneKeep


You basically need to convert your parameters manually. Ideally, abstract this into a controller-method to keep your actual method clean.

Class SomeController < ActionController
  before_filter: cleanup_pagination_params

  def cleanup_pagination_params
    params[:offset] = params[:offset].to_i
    params[:limit]  = params[:limit].to_i
  end

  # Your regular controller methods here
end
like image 36
Satya Kalluri Avatar answered Sep 19 '22 13:09

Satya Kalluri