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 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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With