我正在使用Sinatra和Sequel与PostgreSQL。
在身份验证之后,我想通过打印他们的名字来欢迎用户,但是我不能从数据库中获得用户名的值,而是以哈希的形式出现。
查询是:
current_user = DB[:users].select(:username).where('password = ?', password).first
,得到的数据是:
Welcome, {:username=>"Rich"}
看起来很奇怪,我宁愿阅读“欢迎,富有”。
我在这里做错了什么?我在最后没有“第一次”尝试相同的查询,但这也不起作用。
答案 0 :(得分:1)
您可以从您给出的哈希值中拉出您选择的(单个)列:
current_user = DB[:users].select(:username).where('password=?', password).first[:username]
或者你可以map your results到一组用户名并拉出第一个:
# Using a hash in the filter method is simpler than SQL placeholders.
current_user = DB[:users].filter(password:password).select_map(:username).first
但最好的方法是获取only the user you care about,然后获取名称:
# Using [] on a dataset returns the first row matching the criteria
current_user = DB[:users][password:password][:username]
答案 1 :(得分:0)
尝试Sequel :: Dataset#get。而且,正如Phrogz所指出的,Sequel :: Dataset#where可以接受哈希值(它将安全地转义值以防止注入攻击)。
current_username = DB[:users].where(password: password).get(:username)
还有Sequel :: Dataset#where_single_value,已针对这种确切情况进行了优化:
current_username = DB[:users].select(:username).where_single_value(password: password)