我需要在更新前调用方法来检查PayPal详细信息是否正确。
我在User.rb中添加了这个:
before_update :verify
private
def verify
require 'httpclient'
require 'xmlsimple'
clnt = HTTPClient.new
....
if account_status == "VERIFIED"
current_user.verified = "verified"
current_user.save
flash[:notice] = "Your account is verified"
else
redirect_to :back
flash[:error] = "Sorry, your account is not verified or you entered wrong credentials"
end
else
redirect_to :back
flash[:error] = "Your account is not verified or you entered wrong credentials"
...
end
end
编辑:试过这个:
class RegistrationsController < Devise::RegistrationsController
before_filter :verify, :only => :update
def verify
...
end
end
但它没有打电话。
也许我应该从这里打电话(但我不知道如何以及在哪里):
class RegistrationsController < Devise::RegistrationsController
def create
build_resource
if resource.save
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
redirect_to :back
flash[:error] = "Your email has been already taken!"
end
end
def update
self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
params[:user].delete(:password) if params[:user][:password].blank?
params[:user].delete(:password_confirmation) if params[:user][:password_confirmation].blank?
if resource.update_attributes(params[resource_name])
set_flash_message :notice, :updated if is_navigational_format?
sign_in resource_name, resource, :bypass => true
respond_with resource, :location => after_update_path_for(resource)
else
clean_up_passwords(resource)
respond_with_navigational(resource){ render_with_scope :edit }
end
end
有人会注意到代码中的一些错误吗?
答案 0 :(得分:0)
在User.rb中,使用before_save
宏而不是before_update,因为before_update不存在
还有一件事,在您的用户模型中,flash
无法访问,因为它只是在控制器中注入。你改为抛出验证错误或
class User < ActiveRecord::Base
before_save :verify
private
def verify(record)
#... do checking ... and on error
record.errors ... #is accesable, set your error here if you want to read it in controller
# rise here error if you want
end
end
有关activerecord回调的更多信息
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
答案 1 :(得分:0)
这是正确答案:
class RegistrationsController < Devise::RegistrationsController
before_filter :verify, :only => :update
def verify
...
end
end
感谢您的帮助