开发者

How to search a record in RoR?

开发者 https://www.devze.com 2022-12-14 18:00 出处:网络
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 al

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.


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)


You can use dynamic finders to find user by user_name and password:

@user = User.find_by_user_name_and_password('scott', 'tiger')


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

0

精彩评论

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