5

Sinatra と Sequel を PostgreSQL で使用しています。

認証後、ユーザー名を出力して歓迎したいのですが、データベースからユーザー名の値しか取得できず、ハッシュとして出てきます。

クエリは次のとおりです。

current_user = DB[:users].select(:username).where('password = ?', password).first

結果のデータは次のとおりです。

Welcome, {:username=>"Rich"}

かなり奇妙に見えますが、「ようこそ、リッチ」と読みたいと思います。

ここで何が間違っていますか?最後に「first」を付けずに同じクエリを試しましたが、どちらも機能しません。

4

2 に答える 2

5

与えられたハッシュから選択した(単一の)列を引き出すことができます:

current_user = DB[:users].select(:username).where('password=?', password).first[:username]

または、結果をユーザー名の配列にマップし、最初のものを取得できます。

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

しかし、気になるユーザーだけを取得してから、名前を取得するのが最善の方法です。

# Using [] on a dataset returns the first row matching the criteria
current_user = DB[:users][password:password][:username]
于 2013-06-13T05:01:21.930 に答える