【问题标题】:How to put inline Ruby each loop in an external request?如何将内联 Ruby 每个循环放入外部请求中?
【发布时间】:2012-02-10 05:16:24
【问题描述】:

我正在使用 Rails 3.1 和 paypal_adaptive (https://github.com/tc/paypal_adaptive) gem 来向 Paypal 发出 API 请求。这是交易:我有一个请求,我在控制器中向 Paypal 提出请求。我有一个项目集合(这里是@items),我正在尝试为该集合中的每个项目添加收件人到该请求。这是我的代码:

pay_request = PaypalAdaptive::Request.new

data = {
  "returnUrl" => "http://testserver.com/payments/completed_payment_request",
  "requestEnvelope" => {"errorLanguage" => "en_US"},
  "currencyCode" => "USD",
  "receiverList" => {"receiver"=>[
    @items.each do |item|
      {"email"=>"#{Recipient.find_by_id(item.recip_id).email}", "amount"=>"#{item.price}"},
    end
  ]},
  "cancelUrl"=>"http://testserver.com/payments/canceled_payment_request",
  "actionType"=>"PAY",
  "ipnNotificationUrl"=>"http://testserver.com/payments/ipn_notification"
}

pay_response = pay_request.pay(data)

if pay_response.success?
  redirect_to pay_response.approve_paypal_payment_url
else
  puts pay_response.errors.first['message']
  redirect_to failed_payment_url
end

...但这不起作用。如何在此请求中正确插入 Ruby 语法?

(抱歉标题含糊不清。我不确定我在提出什么样的请求(也许是 AJAX?))

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 paypal


    【解决方案1】:

    只需将所有项目收集到一个变量中并将其设置为“接收者”键的值:

    recipients = @items.each do |item|
      {"email"=>"#{Recipient.find_by_id(item.recip_id).email}", "amount"=>"#{item.price}"}
    end
    
    ...
    
    "currencyCode"=>"USD",  
    "receiverList"=>{"receiver"=> recipients},
    "cancelUrl"=>"http://testserver.com/payments/canceled_payment_request",
    

    【讨论】:

    • 好主意。我得到了一个错误:它给了我一堆语法错误,意外的',',期待keyword_end异常。你知道为什么会这样吗?
    • 修正了我的例子。第二行有一个逗号。话虽如此,这是一个非常基本的问题。通过查看一本好的红宝石书或资源(即:免费的 Pickaxe 书:ruby-doc.org/docs/ProgrammingRuby),您可以节省大量等待此类问题答案的时间
    猜你喜欢
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    相关资源
    最近更新 更多