I do not understand why the group method is not available.

Asked 2 years ago, Updated 2 years ago, 465 views

Sorry for the rudimentary question.
Connection.group(:user_id) causes
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

Due to the above relationships, the following situations occur:

irb(main): 038:0>Connection.group(:user_id)
  Connection Load (1.2ms) SELECT`connections`.* FROM`connections`GROUP BY`connections`.`user_id`
(Object does not 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: "[email protected]",
  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: "[email protected]",
  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>]

In this way, if you try to GROUP BY user_id itself,
Object doesn't support#inspect, but
Use this as an internal connection to the User to work properly.
This time, I would like to obtain a connection that does not overlap with users.
Why doesn't the former move?
Also, how can I get a Connection that does not overlap users?
Thank you for your cooperation.

By the way, this is the code that comes out when I looked it up using group.

User.group(:sex)

That's why it's similar to this

UserProfile.group(:sex)#User has_many:user_profiles
User.group(:email)

I have also tried
Both were Object doesn't support inspect.

ruby-on-rails mysql

2022-09-30 22:03

1 Answers

This has been resolved.
It's really rudimentary, and group cannot be used alone in the first place.
Works with aggregation methods

Connection.group(:user_id).minimum(:id).values

Therefore, it is possible to obtain the smallest connection.id summarized in user_id.
(maximum(:id) to get the maximum id.)
I also looked into how to return it with ActiveRecord_Relation, but
It didn't work out well, so I'll study it again.
Thank you.


2022-09-30 22:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.