1
我使用ActiveModel而不是ActiveRecord。而我的模式是:如何最好地处理Ruby中的HTTP响应?
class User
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
validates :name, :presence => true, :length => { :maximum => 50 }
validates :email, :presence => true,
:format =>
{
:with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
}
validates :password, :presence => true, :confirmation => true,
:length =>
{
:within => 6..40
}
attr_accessor :name, :email, :password, :password_confirmation
def initialize(attributes = {})
@name = attributes[:name]
@email = attributes[:email]
@password = attributes[:password]
@password_confirmation = attributes[:password_confirmation]
end
def persisted?
false
end
def save
# createUser calls RESTful HTTP server and gets back JSON in http response's body
response = createUser(self.name, self.email, self.password)
end
end
,并在下面当我尝试处理由上面的保存方法返回此响应我的users_controller.rb,它打乱了我的模型的验证密码和password_confirmation。
def create
@user = User.new(params[:user])
response = @user.save
parsed_response_body = ActiveSupport::JSON.decode(response.body)
# response body I have is {"ok":"ok message"} OR {"error":"error message"}
message = parsed_response_body["error"]
if @user.valid? && message.nil?
flash[:success] = message
redirect_to signup_path
else
@user.password = ""
@user.password_confirmation = ""
flash[:error] = message
render :action => 'new'
end
end
下面是控制器代码,不破坏验证;其中@ user.save在这种情况下返回true。
def create
@user = User.new(params[:user])
if @user.valid? && @user.save
flash[:success] = "Done"
redirect_to signup_path
else
@user.password = ""
@user.password_confirmation = ""
flash[:error] = "Not Done"
render :action => 'new'
end
end
我很感激,如果有人可以帮助我这个..
你的问题,具体是什么? –
@mark我的问题是,为什么当我在控制器中添加处理响应的代码时,它会打破用户密码和password_confirmation验证?我在处理回复时做错了什么? –