class Project < ActiveRecord::Base
has_many :photos, -> { order(main: :desc, id: :asc) }, as: :photoable, class_name: 'Photo', dependent: :destroy
class Photo < ActiveRecord::Base
belongs_to :photoable, polymorphic: true
projects = Project.limit(10).includes(:photos)
SELECT "projects".* FROM "projects" WHERE "projects"."is_deleted" = $1 LIMIT 10 [["is_deleted", "f"]]
Photo Load (0.5ms) SELECT "photos".* FROM "photos" WHERE "photos"."photoable_type" = 'Project' AND "photos"."photoable_id" IN (1, 403, 371, 8784, 12, 34, 11, 1111, 31, 22) ORDER BY "photos"."main" DESC, "photos"."id" ASC
projects.first.photo
Photo Load (0.6ms)
它正在发送一个在(0.6ms)内执行的数据库查询。知道如何避免数据库查询吗?
我正在使用Rails 4.2.6&amp; Ruby 2.3.1p112
答案 0 :(得分:0)
projects = Project.includes(:photos).limit(10)
然后遍历项目。它不会触发另一个查询。
projects.each do |project|
project.photo
end