我需要在 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
我的错误在哪里?