简体   繁体   English

Rails 自动将查询字符串参数转换为整数

[英]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?有没有办法确保这些值是整数,否则会抛出 400 错误,也许是通过使用 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.就像上面的评论者@Litmus 一样,我建议使用 Ruby gem(例如kaminari)来管理分页。

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 .请注意,诸如"foo"字符串将被转换为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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM