Frage

I have one application with the following code:

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

It sends data to my other application via the URL params query string. This is what the controller method of that other application looks like:

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

I get this error:

<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>

I tried using both raw and html_safe on the params[:quantity] and other params, but still I get the error. Note I had to use URI.encode(url) because URI.parse(url) returned bad uri probably because of the array of unit_types.

War es hilfreich?

Lösung

Change:

 quantity.times do |index|

To:

 quantity.to_i.times do |index|

The reason you are having this problem is because you are treating the params values as the types that you originally tried to send, but they are actually always going to be strings. Converting back to the expected 'type' solves your problem.

However, you have some more fundamental problems. Firstly, you are trying to send an array by simply formatting it to a string. However, this is not the format that the receiving application expects to translate back to an array. Secondly, there is duplication in your request - you don't need to specify a quantity. The length of the array itself is the quantity. A better method would be to build your url like this:

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('&')

On the receiving side, you can do this:

def create_units_from_paypal
  unit_types = params[:unit_types]
  airtime_plan = params[:airtime_plan]
  quantity = unit_types.try(:length) || 0

  #...
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top