views:

19

answers:

1

Hi,

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!

+1  A: 

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.

Rishav Rastogi
Thanks. For the password issue, sure I'm just messing around to learn Rails, it's not a production code but I'll probably take a look at those plugins.
Amokrane