简体   繁体   English

活动记录查询问题

[英]Problem with Active Record Querying

I am building a little application in Rails and what I am trying to do now is authenticate a user. 我正在Rails中构建一个小应用程序,现在我要尝试的是对用户进行身份验证。

So I got this method in the controller class: 所以我在控制器类中得到了这个方法:

def login
      if @user = User.authenticate(params[:txt_login], params[:txt_password])
          session[:current_user_id] = @user.id
          redirect_to root_url
      end
   end

Here is the definition of authenticate method (inside the User model class): 这是authenticate方法的定义(在User模型类内部):

 def self.authenticate(username, password)
      @user = User.where(["username = ? AND password = ?", username, password])
      return @user
  end

The problem is that I get an error message saying: 问题是我收到一条错误消息:

undefined method `id' for #<ActiveRecord::Relation:0x92dff10>

I confirm that the user I was trying to log in really exists in the database (besides it tries to get the id of a user and this instruction is wrapped inside an if in case 0 users are returned from the authenticate method). 我确认我要登录的用户确实存在于数据库中(除了它尝试获取用户的ID之外,如果从authenticate方法返回0个用户,则此指令包装在一个if中)。

Why am I obtaining this error message? 为什么我会收到此错误消息? Knowing that when I change the User.where by User.find it works fine! 知道当我通过User.find更改User.where ,它可以正常工作!

Thank you! 谢谢!

User.where("some_conditions") will return an array of User objects ( in simple terms ) , A User.find can return an array or a single object.( I am not sure because i don't see how you are using it ) User.where("some_conditions")将返回一个User对象数组(简单来说), User.find可以返回一个数组或单个对象。(我不确定,因为我看不到您如何使用它)

As far what you see is ActiveRecord::Relation, this is what is returned when we call a find or a where or a order method on Rails 3 Models. 就您所看到的是ActiveRecord :: Relation,这是当我们在Rails 3 Models上调用find或where或order方法时返回的结果。

Also, You are storing password as a plain string which is a bad idea, you should use some available rails authentication plugins like Devise or Authlogic. 另外,您将密码存储为纯字符串,这不是一个好主意,您应该使用一些可用的Rails身份验证插件,例如Devise或Authlogic。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM