2012-09-15 88 views
0

控制器代碼:Ruby on Rails的if語句總是返回true

def create 

    if current_user.id != params[:friend_id] 
     @return = { :curr_user_id => current_user.id, :params_id => params[:friend_id], :debug => 1 } 
    else 
     @return = { :curr_user_id => current_user.id, :params_id => params[:friend_id], :debug => 2 } 
    end 

    render :json => ActiveSupport::JSON.encode(@return) 

    end 

所以current_user.id是和params[:friend_id]正在通過Ajax調用傳遞其價值也

問題是它在這種情況下應該返回false時總是返回true ......是否有任何與數字1被解析爲字符串而不是整數有關的事情?

回答

6

PARAMS是總是串,使用:

if current_user.id != Integer(params[:friend_id]) 

我不建議to_i,看看爲什麼:

"abc".to_i  # => 0 which is unexpected 
Integer("abc") # => raises error, which is fine