如何在外部请求中将每个循环放入内联Ruby?

时间:2012-01-14 04:15:54

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

我使用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可能会?)

1 个答案:

答案 0 :(得分:0)

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

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