如何使用 Sequel 从数据库中选择一个字段

use*_*663 5 ruby postgresql sinatra sequel

我在 PostgreSQL 中使用 Sinatra 和 Sequel。

身份验证后,我想通过打印他们的姓名来欢迎用户,但我不能只从数据库中获取用户名的值,它以散列形式出现。

查询是:

current_user = DB[:users].select(:username).where('password = ?', password).first
Run Code Online (Sandbox Code Playgroud)

得到的数据是:

Welcome, {:username=>"Rich"}
Run Code Online (Sandbox Code Playgroud)

这看起来很奇怪,我更喜欢读“欢迎,丰富”。

我在这里做错了什么?我在最后尝试了没有“first”的相同查询,但这也不起作用。

Phr*_*ogz 5

您可以从给定的哈希中拉出您选择的(单个)列:

current_user = DB[:users].select(:username).where('password=?', password).first[:username]
Run Code Online (Sandbox Code Playgroud)

或者您可以将结果映射到一组用户名并提取第一个:

# Using a hash in the filter method is simpler than SQL placeholders.
current_user = DB[:users].filter(password:password).select_map(:username).first
Run Code Online (Sandbox Code Playgroud)

但最好的方法是获取你关心的用户,然后获取名称:

# Using [] on a dataset returns the first row matching the criteria
current_user = DB[:users][password:password][:username]
Run Code Online (Sandbox Code Playgroud)