【发布时间】:2020-02-24 08:49:55
【问题描述】:
模型结构:
Comment 模型有 belongs_to 关系
和Resource 模型没有任何关系。
class Comment < ApplicationRecord
belongs_to :resource
end
Class Resource < ApplicationRecord
#No relation
end
这是我的查询: (希望这不是我使用的 n+1 包含)
comments = Comment.where(id: [5,6,7]).includes(:resource)
Hash[comments.map { |comment|
[comment.id, comment.resource] if comment.resource
}]
我得到的输出是这样的:
其中5和6是comment_id,其他是resource _attributes
5=>
#<Resource:0x00007fa9b2a93518
id: 3,
url: "http://url.com",
description: "og:description",
title: "title",
site_name: "og:site_name",
image_url: "http://imageurl.com",
video_url: nil,
created_at: Mon, 28 Oct 2019 07:44:16 UTC +00:00,
updated_at: Mon, 28 Oct 2019 07:44:16 UTC +00:00,
embed_html: nil,
url_hash: "df5ac6d4a1313ecb9949312d0258416a248333f68ae39aa1c7acd818e7d997e7",
user_id: nil>,
6=>
#<Resource:0x00007fa9b2a92fa0
id: 4,
url: "http://url.com",
description: "og:description",
title: "title",
site_name: "og:site_name",
image_url: "http://imageurl.com",
video_url: nil,
created_at: Mon, 28 Oct 2019 07:44:16 UTC +00:00,
updated_at: Mon, 28 Oct 2019 07:44:16 UTC +00:00,
embed_html: nil,
url_hash: "df5ac6d4a1313ecb9949312d0258416a248333f68ae39aa1c7acd818e7d997e7",
user_id: nil>}
但我需要更优化的查询和输出应该是这样的:
5=>
#<Resource:0x00007fa9b2a93518
id: 3,
url: "http://url.com",
description: "og:description",
,
6=>
#<Resource:0x00007fa9b2a92fa0
id: 4,
url: "http://url.com",
description: "og:description"
}
【问题讨论】:
标签: mysql ruby-on-rails ruby optimization