简体   繁体   中英

How to search a record in RoR?

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 )

您可以使用动态查找器通过user_name和密码查找用户:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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