概要
初歩的な質問で申し訳ありません。
Connection.group(:user_id)
を実行すると、
Object doesn't support #inspect
になってしまいます。
環境
Ruby 3.1.0
Ruby on Rails 6.1.4
該当のコード
model
class User < ApplicationRecord
has_many :connections
end
class Connection < ApplicationRecord
belongs_to :user
end
上記の関係性で以下のような状況になります。
irb(main):038:0> Connection.group(:user_id)
Connection Load (1.2ms) SELECT `connections`.* FROM `connections` GROUP BY `connections`.`user_id`
(Object doesn't support #inspect)
=>
irb(main):039:0> User.joins(:connections).group(:user_id)
User Load (0.7ms) SELECT `users`.* FROM `users` INNER JOIN `connections` ON `connections`.`user_id` = `users`.`id` GROUP BY `user_id`
=>
[#<User:0x0000000116f47d58
id: 1,
email: "demo-1@example.jp",
created_at: Thu, 21 Apr 2022 15:26:53.000000000 JST +09:00,
updated_at: Tue, 17 May 2022 08:49:46.000000000 JST +09:00>,
#<User:0x0000000116f47c90
id: 2,
email: "demo-2@example.jp",
created_at: Thu, 21 Apr 2022 15:28:27.000000000 JST +09:00,
updated_at: Tue, 17 May 2022 08:51:19.000000000 JST +09:00>]
このように、Connection
自体をuser_id
でGROUP BYしようとすると
Object doesn't support #inspect
になってしまいますが、
これをUser
に内部結合として使うときちんと動作します。
今回はUserが重複しないConnectionを取得したいのですが、
前者はなぜ動かないのでしょうか?
また、「Userが重複しないConnection」を取得するにはどのような方法がありますでしょうか?
よろしくご教授ください。
補足
ちなみにgroup
の使い方で調べた時に出てくるコードで、
User.group(:sex)
というのがあり、これに似たものとして
UserProfile.group(:sex) #User has_many :user_profilesです
User.group(:email)
なども試してみましたが、
いずれもObject doesn't support inspect
でした。