【问题标题】:How to fetch objects in joins?如何在连接中获取对象?
【发布时间】:2019-11-07 11:56:53
【问题描述】:

这是我的架构:

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

用户.rb

No Association.

查询:

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)

输出:

=> {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 是user,115 是mentionable_id。

我怎样才能通过 group_by 提及_id 获得完整的用户对象?

预期:

=> {155=>
      [#<User:0x00007ff51a309de8 id: 110, name: "abc", email: 'xyz@mail.com', deleted_at: nil>,
      #<User:0x00007ff51a3092f8 id: 112, name: "abc", email: 'xyz@mail.com', deleted_at: nil>],
 156=>[#<User:0x00007ff51a3098e8 id: 111, name: "abc", email: 'xyz@mail.com', deleted_at: nil>]}

【问题讨论】:

    标签: mysql ruby-on-rails ruby object


    【解决方案1】:

    您需要通过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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-17
      • 2012-12-12
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多