2011-07-30 36 views
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 

我很感激,如果有人可以幫助我這個..

+0

你的問題,具體是什麼? –

+0

@mark我的問題是,爲什麼當我在控制器中添加處理響應的代碼時,它會打破用戶密碼和password_confirmation驗證?我在處理回覆時做錯了什麼? –

回答

0

它看起來像你對我需要調用在savesuper或者它實際上並不會嘗試驗證:

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