我有两个型号
class Course
belongs_to :content_picture
end
class ContentPicture
end
当我尝试加载课程并急切加载所有图片时,我得到N + 1个查询,我想在两个查询中进行此操作
我尝试过include,join,eager_load
结果:
Course.all
给出
Course Load (1.4ms) SELECT "courses".* FROM "courses"
ContentPicture Load (1.4ms) SELECT "content_pictures".* FROM "content_pictures" WHERE "content_pictures"."id" = $1 LIMIT 1 [["id", 8]]
ContentPicture Load (1.6ms) SELECT "content_pictures".* FROM "content_pictures" WHERE "content_pictures"."id" = $1 LIMIT 1 [["id", 7]]
包括:
Course.includes(:content_picture).all
结果:
Course.includes(:content_picture).all
Course Load (1.6ms) SELECT "courses".* FROM "courses"
ContentPicture Load (1.1ms) SELECT "content_pictures".* FROM "content_pictures" WHERE "content_pictures"."id" = $1 LIMIT 1 [["id", 8]]
ContentPicture Load (1.0ms) SELECT "content_pictures".* FROM "content_pictures" WHERE "content_pictures"."id" = $1 LIMIT 1 [["id", 7]]
随着加载和加入,它是一样的。
答案 0 :(得分:1)
由于来自@MrYoshiji的暗示,我发现这是因为after_initialize阻止造成的
after_initialize do
self.content_picture ||= ContentPicture.new
end
删除块后,查询工作正常。
答案 1 :(得分:0)
你会尝试这个
module.exports = {
development: {
client: 'pg',
connection: 'postgres://localhost/eka_dev',
migrations: {
tableName: 'knex_migrations'
}
},
test: {
client: 'pg',
connection: 'postgres://localhost/eka_test',
migrations: {
tableName: 'knex_migrations'
}
},
production: {
client: 'pg',
connection: process.env.DATABASE_URL,
migrations: {
tableName: 'knex_migrations'
}
}
};