2011-12-04 116 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客户端在每个请求。