2013-05-06 50 views
0

我有下面的代码一个应用:如何从params散列中删除特殊字符?

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 

它发送数据通过网址参数的查询字符串我的其他应用程序。这是什么,其他应用程序的控制方法是这样的:

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 &quot;3&quot;:String</pre> 


<p><code>Rails.root: /Users/johnmerlino/Documents/github/my_app</code></p> 

我尝试使用的params[:quantity]和其他paramsrawhtml_safe,但我仍然得到错误。注意我不得不使用URI.encode(url),因为URI.parse(url)返回了不好的uri,可能是因为unit_types的数组。

回答

1

变化:

quantity.times do |index| 

要:

quantity.to_i.times do |index| 

原因你有这个问题,因为你是治疗的PARAMS值作为您最初试图向其发送的类型,但是它们是实际上总是会成为字符串。转换回预期的'类型'可以解决您的问题。

但是,你有一些更基本的问题。首先,你试图通过简单的格式化一个字符串来发送一个数组。但是,这不是接收应用程序期望转换回数组的格式。其次,你的要求有重复 - 你不需要指定数量。阵列本身的长度的数量。更好的方法是建立你的网址是这样的:

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 

    #...