0

我需要在 before_save 之前验证用户数据。我只保存 paypal_email,不保存名字和姓氏。

我在模型中添加了 before_save 过滤器:

   attr_accessible :paypal_email, :first_name, :last_name
   attr_accessor :first_name
   attr_accessor :last_name

   before_save :verify

并添加了验证方法:

   protected
 def verify

require 'httpclient'
require 'xmlsimple'

clnt = HTTPClient.new

header =  {"X-PAYPAL-SECURITY-USERID" => "1111111111",
                "X-PAYPAL-SECURITY-PASSWORD" => "111111",
               "X-PAYPAL-SECURITY-SIGNATURE" => "11111",
               "X-PAYPAL-REQUEST-DATA-FORMAT" => "NV",
               "X-PAYPAL-RESPONSE-DATA-FORMAT" => "XML",
               "X-PAYPAL-APPLICATION-ID" =>  "APP-2J632856DC989803F"
                }
 logger.info(@user.first_name)               
 data = {"emailAddress" => self.paypal_email,
       "firstName"=> self.first_name,
       "lastName" => self.last_name,
       "matchCriteria" => "NAME",         
       "requestEnvelope.errorLanguage" => "en_US"}

 uri = "https://svcs.paypal.com/AdaptiveAccounts/GetVerifiedStatus"
 res = clnt.post(uri, data, header)
 @xml = XmlSimple.xml_in(res.content)

  if res.status == 200
    if @xml['accountStatus']!=nil
      account_status = @xml['accountStatus'][0]
      if account_status == "VERIFIED" 
        redirect_to :back
        flash[:success] = "Your account is verified"
      else 
        redirect_to :back
        flash[:error] = res.content
      end

    else
      redirect_to :back
       flash[:error] = res.content
   end  
   else 
    flash[:error] = "Oops! Can't conntect to PayPal"
  end

 end

编辑

    def create
     @user = User.new(params[:user])
     if @user.valid?
         @user.save
         flash[:notice] = "success"
     else
         render :new
         flash[:error] = "error"

 end

什么给了我错误:

     undefined method `first_name' for nil:NilClass

我的错误在哪里?

4

1 回答 1

1

由于您在您的模型中,请替换@user.first_nameself.first_name甚至first_name

其他问题

  • 第三方服务调用应该存在于后台作业中。

  • flash在模型中是未知的,它属于控制器,也属于redirect.

  • redirect_to :back,这不是一个好习惯:有些浏览器不发送引荐来源网址

于 2012-08-30T13:03:06.883 回答