2011-12-04 166 views
0

這裏是我的控制器代碼檢查用戶的登錄信息如何存儲find_by_sql_results在會話變量

def validateLogin 
    @email = params[:userEmail1] 
    @pass = params[:userPassword1] 

    if params[:userEmail1] != nil 
    valid_user = Userprofile.find_by_sql(["select * from userprofiles where userEmail=? and userPassword=?", @email, @pass]) 
    if valid_user.count > 0 
     session[:email] = @email 
     session[:uid] = valid_user.id 
     session[:userType] = valid_user.userType # usertype is a column in userprofiles table 
     # But here i am not receiving the usertype it gives error that undefined variable usertype. 
     redirect_to "/userhomes/" 
    else 
     flash[:message] = "Either email or password is incorrect" 
     redirect_to '/' 
    end 
else 
    flash[:message]="Fields can not be blank" 
    render :action=>'defaults' 
end 

請幫

session[:userType] = valid_user.userType 
# Error: (usertype is a column in userprofiles table) 

但是在這裏我無法接收提示錯誤的用戶類型是未定義的變量usertype。

回答

2

您看到此錯誤是因爲您收到find_by_sql中的一組對象。你甚至可以檢查if子句中的數組大小。

從你的代碼我認爲你只期望一個返回的對象。但你仍然需要從陣列得到它,像這樣:

profiles = Userprofile.find_by_sql(["select * from userprofiles where userEmail=? and userPassword=?", @email, @pass]) 
if profiles.count > 0 
    user_profile = profiles[0] 
    #... your other stuff 
end 

這也更好的用途Rails的成語,尤其是ActiveRecord的原樣被inteded使用是讓它構造SQL本身是另一個變種通常更安全,不易出錯和緩存。

不是你寫你正在使用的Rails的版本,但對於Rails的2.3.x版本,它看起來像這樣

user_profile = Userprofile.first(:conditions => {:userEmail => @email, :userPassword => @pass}) 

對於Rails開發3.x中,它看起來像這樣:

user_profile = Userprofile.where(:userEmail => @email, :userPassword => @pass).first 

這兩個變體都希望你有一個叫做Userprofile的模型,你通常需要在Rails中有效地處理數據庫對象。這兩個查詢都是從查詢返回的第一行創建一個新的模型實例(這就是first所做的)。

一般來說,你應該在網上得到一本書或一些指南,並學習如何正確使用ActivRecord。請注意,Rails 2.3和Rails 3之間的API已經發生了嚴重的變化,因此請確保爲您的實際Rails版本使用指南。

作爲最後的建議,你不應該在會話中存儲實際的ActiveRecord對象。他們需要在商店中序列化並在訪問時反序列化。是什麼讓它很難(或不可能跟蹤對象引用)

另外,Rails默認使用cookie會話存儲,這意味着整個會話數據存儲在客戶端的cookie中,其中的數據完全支持任何人都可以訪問cookie,因爲它只是用來限制篡改數據的簽名,但沒有加密。因此,在你的情況下,任何人都可以準備(未加密的)密碼。

取代存儲模型對象,您應該將其存儲爲id,然後從數據庫中獲取實際(最新)對象,而不是每個請求。這更容易,可以避免緩存不一致(如果用戶更改密碼會發生什麼情況)以及可能比從此傳輸巨大會話cookie更快e客戶端在每個請求。