Ruby on rails 如何从params散列中删除特殊字符?
我有一个具有以下代码的应用程序:Ruby on rails 如何从params散列中删除特殊字符?,ruby-on-rails,sanitize,Ruby On Rails,Sanitize,我有一个具有以下代码的应用程序: quantity = 3 unit_types = ['MarineTrac','MotoTrac','MarineTrac'] airtime_plan = 'Monthly Airtime Plan' url = "http://localhost:3000/home/create_units_from_paypal?quantity=#{quantity}&unit_types=#{unit_types}&airtime_plan=#{a
quantity = 3
unit_types = ['MarineTrac','MotoTrac','MarineTrac']
airtime_plan = 'Monthly Airtime Plan'
url = "http://localhost:3000/home/create_units_from_paypal?quantity=#{quantity}&unit_types=#{unit_types}&airtime_plan=#{airtime_plan}"
begin
resp = Net::HTTP.get(URI.parse(URI.encode(url.strip)))
resp = JSON.parse(resp)
puts "resp is: #{resp}"
true
rescue => error
puts "Error: #{error}"
return nil
end
它通过URL参数查询字符串将数据发送到我的其他应用程序。这是另一个应用程序的控制器方法的外观:
def create_units_from_paypal
quantity = params[:quantity]
unit_types = params[:unit_types]
airtime_plan = params[:airtime_plan]
quantity.times do |index|
Unit.create! unit_type_id: UnitType.find_by_name(unit_types[index]),
airtime_plan_id: AirtimePlan.find_by_name(airtime_plan),
activation_state: ACTIVATION_STATES[:activated]
end
respond_to do |format|
format.json { render :json => {:status => "success"}}
end
end
我得到这个错误:
<h1>
NoMethodError
in HomeController#create_units_from_paypal
</h1>
<pre>undefined method `times' for "3":String</pre>
<p><code>Rails.root: /Users/johnmerlino/Documents/github/my_app</code></p>
我尝试在params[:quantity]
和其他params
上同时使用raw
和html\u-safe
,但还是出现了错误。注意:我不得不使用URI.encode(url)
,因为URI.parse(url)
返回了错误的URI,可能是因为单元类型的数组。更改:
quantity.to_i.times do |index|
致:
出现此问题的原因是,您将params值视为最初尝试发送的类型,但实际上它们始终是字符串。转换回预期的“类型”可以解决您的问题
但是,您还有一些更基本的问题。首先,您试图通过将数组格式化为字符串来发送数组。但是,这不是接收应用程序希望转换回数组的格式。其次,您的请求中存在重复-您不需要指定数量。数组本身的长度就是数量。更好的方法是像这样构建url:
def create_units_from_paypal
unit_types = params[:unit_types]
airtime_plan = params[:airtime_plan]
quantity = unit_types.try(:length) || 0
#...
url = 'http://localhost:3000/home/create_units_from_paypal?'
url << URI.escape("airtime_plan=#{airtime_plan}") << "&"
url << unit_types.map{|ut| URI.escape "unit_types[]=#{ut}" }.join('&')
def create_units_from_paypal
unit_types = params[:unit_types]
airtime_plan = params[:airtime_plan]
quantity = unit_types.try(:length) || 0
#...