2013-05-06 46 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 

    #...