LoginSignup
0
0

More than 5 years have passed since last update.

where後に配列に入っている値をハッシュ形式にする方法。(レコード1件のみ時)

Posted at

whereで値を取得した後は配列に入っています。
下記のコードですが、Entryモデル中の1つのroom_idには送信者、受信者のuser_idがある。
(1つのroom_idにつき最小、最大2名のみ)
したがって自分以外のuser_idを残すためにwhere.notで自分のuser_idを取得しないようにしている。

@room_idには1つのuser_idしかないのがわかっている中で、
each文での取り出しはスマートではない。

コード
    28:   @room_id = Entry.where(room_id: params[:id]).where.not(user_id: current_user.id)
    29:   @room_id.each do |user|
    30:   @reception_user = User.find(user.user_id)
 => 31:   binding.pry
    32:   end
    33:   link "#{@reception_user.name}さんとのチャットルーム", user_room_path

@room_idに入っている値です。

> @room_id
=> [#<Entry:0x00007ff76be33a40
  id: 2,
  user_id: 2,
  room_id: 1,

試したこと

配列からハッシュにするto_hメソッドを見つけて試したが、無理な様子。

@room_id = Entry.where(room_id: params[:id]).where.not(user_id: current_user.id)
@room = @room_id.to_h

エラー内容

wrong element type Entry (expected array)

解決法

レコードが1件しかないのがわかっているので、firstで配列を展開から展開されハッシュ形式で@entryに渡っている。

@room_id = Entry.where(room_id: params[:id]).where.not(user_id: current_user.id).first
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0