Reputation: 1332
This is my schema :
Mention.rb
belongs_to :user
create_table "mentions", force: :cascade do |t|
t.integer "user_id", limit: 4
t.integer "mentionable_id", limit: 4
t.string "mentionable_type", limit: 191
t.datetime "created_at"
t.datetime "updated_at"
t.datetime "deleted_at"
end
User.rb
No Association.
Query:
mentions = Mention.joins(:user).where(mentions: {mentionable_type: 'Comment', mentionable_id: @comments_ids}).select('users.*, mentions.mentionable_id AS comment_id').group_by(&:comment_id)
Output :
=> {155=>
[#<Mention:0x00007ff51a309de8 id: 110, created_at: Thu, 07 Nov 2019 10:19:46 UTC +00:00, updated_at: Thu, 07 Nov 2019 10:19:46 UTC +00:00, deleted_at: nil>,
#<Mention:0x00007ff51a3092f8 id: 112, created_at: Thu, 07 Nov 2019 10:19:46 UTC +00:00, updated_at: Thu, 07 Nov 2019 10:19:46 UTC +00:00, deleted_at: nil>],
156=>[#<Mention:0x00007ff51a3098e8 id: 111, created_at: Thu, 07 Nov 2019 10:19:46 UTC +00:00, updated_at: Thu, 07 Nov 2019 10:19:46 UTC +00:00, deleted_at: nil>]}
id:110
that is here in the output is of user
and 115
is mentionable_id
.
How can I get complete user object with group_by mentionable_id ?
Expected:
=> {155=>
[#<User:0x00007ff51a309de8 id: 110, name: "abc", email: '[email protected]', deleted_at: nil>,
#<User:0x00007ff51a3092f8 id: 112, name: "abc", email: '[email protected]', deleted_at: nil>],
156=>[#<User:0x00007ff51a3098e8 id: 111, name: "abc", email: '[email protected]', deleted_at: nil>]}
Upvotes: 1
Views: 42
Reputation: 4709
You need to query through User
:
User.joins(:mentions)
.where(mentions: { mentionable_type: 'Comment', mentionable_id: @comments_ids })
.select('users.*, mentions.mentionable_id AS comment_id')
.group_by(&:comment_id)
Upvotes: 1