如何最好地处理Ruby中的HTTP响应?

时间:2011-07-30 12:20:02

标签: ruby ruby-on-rails-3

我正在使用ActiveModel而不是ActiveRecord。我的模型是:

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中,当我尝试处理上面的save方法返回的响应时,它会弄乱我的模型对password和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

如果有人能帮助我,我会感激不尽。

1 个答案:

答案 0 :(得分:0)

我认为您需要在super中致电save,否则它实际上不会尝试验证:

def save
    super

    # createUser calls RESTful HTTP server and gets back JSON in http response's body
    response = createUser(self.name, self.email, self.password)
end