开发者

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.

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):

 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).

Why am I obtaining this error message? Knowing that when I change the User.where by User.find it works fine!

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 )

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜