Reputation: 30568
I know that I can use Query language to find the record I want. I am doing a login page, I want to find the record which match the user name and password, but I don't want to loop all the elements to find out the user I want (<% @users.each do |user| %>), wt should I do in RoR, except typing SQL.
Upvotes: 0
Views: 570
Reputation: 25377
While the other answers provided by Sam and Chandra are technically correct, both solutions implies that passwords are stored in plain text--which is a very bad idea. If somebody who shouldn't gets access to your database, they'll have a full set of usernames (and potentially email addresses), combined with all of their passwords.
Instead, consider using an algorithm to make sure your password is encrypted in the database, such as bcrypt. You'll need the bcrypt-rub gem to use it.
You should also consider leaving out the password from the query altogether. This is good practice as it provides an extra level of security; SQL injections become more difficult to perform. If users have unique usernames, just fetching the username should return the same object, after which you can check if the password is correct:
@user = User.find_by_username(params[:username])
if @user.password == params[:password]
# do something
else
# do something else
end
Ideally, you should both use bcrypt and leave out the password from the query. How to do this is described in the bcrypt-ruby readme on GitHub (the link I provided).
Upvotes: 0
Reputation: 17577
You can use dynamic finders to find user by user_name and password:
@user = User.find_by_user_name_and_password('scott', 'tiger')
Upvotes: 3
Reputation: 131112
perhaps:
User.first(:conditions => {:login => 'ted', :password => 'secret'})
# returns nil for no match and first match for a good record
# make sure there is a unique index on login
For authentication I would strongly recommend authlogic (railscast)
Upvotes: 3