简体   繁体   中英

Why I can't use root_path in User instance method?(undefined local variable or method)

I need to call method for user, which has email parametr. It is function for paying in PayPal and I'm setting return url and cancel url.

Here is my method, in user.rb:

   def pay email
require 'httpclient'
require 'xmlsimple'
clnt = HTTPClient.new
credentials = {
    'USER' => 'payer_1342623102_biz_api1.gmail.com',
   'PWD' => '1342623141',
   'SIGNATURE' => 'Ay2zwWYEoiRoHTTVv365EK8U1lNzAESedJw09MPnj0SEIENMKd6jvnKL '
 }

header =  {"X-PAYPAL-SECURITY-USERID" => "payer_1342623102_biz_api1.gmail.com",
               "X-PAYPAL-SECURITY-PASSWORD" => "1342623141",
               "X-PAYPAL-SECURITY-SIGNATURE" =>"Ay2zwWYEoiRoHTTVv365EK8U1lNzAESedJw09MPnj0SEIENMKd6jvnKL ",
               "X-PAYPAL-REQUEST-DATA-FORMAT" => "NV",
               "X-PAYPAL-RESPONSE-DATA-FORMAT" => "XML",
               "X-PAYPAL-APPLICATION-ID" =>  "APP-80W284485P519543T"
                }
data = {"actionType" => "PAY",
           "receiverList.receiver(0).email"=> email,
           "receiverList.receiver(0).amount" => "10",
           "currencyCode" => "USD",
           "cancelUrl" => root_path,
           "returnUrl" => root_path,
           "requestEnvelope.errorLanguage" => "en_US"}
uri = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay"
res = clnt.post(uri, data, header)
@xml = XmlSimple.xml_in(res.content)
payKey = @xml["payKey"].to_s()
payKey = payKey.tr("[]", "")
payKey = payKey[1..20]
redirect_to "https://sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=#{payKey}"
 end

and I get error:

      undefined local variable or method `root_path'

Why I can't use this method ? And why I can't use redirect_to ?

I don't think root_path or root_url is available by default from within a model class. This is by design, since your model should not have knowledge of the controller/view/session-like operations. You can get access to the root_url by including this in the model though:

include Rails.application.routes.url_helpers

A better solution would be to pass this information into the order.pay method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM