Rails auto convert query string params to integers
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
Try this: Repair numeric param values converted into string
repair_nested_params({id: '11', age: '25'}) # Sample
def repair_nested_params(obj)
obj.each do |key, value|
obj[key] = parse_string(value)
end
end
def parse_string(value)
return repair_nested_params(value) if value.is_a?(Hash)
return value.map(&method(:repair_nested_params)) if value.is_a?(Array)
return value unless value.is_a?(String)
is_numeric = value.match?(/\A[-+]?\d*\.?\d+\z/)
return value unless is_numeric
(value.to_f % 1).positive? ? value.to_f : value.to_i
end
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
.