请有人帮助我:
使用Rails我开发了一个应用程序。
我的模型如下所示:
class Score < ActiveRecord::Base
belongs_to :song
belongs_to :user
end
class Song < ActiveRecord::Base
has_one :gsong
has_many :scores
end
class Gsong < ActiveRecord::Base
belongs_to :song
end
class user < ActiveRecord::Base
has_many :scores
end
我的ScoresController
:
class scoresController < ApplicationController
def index
id = current_user.id
@scores = score.where(:user_id => id)
render :json => {
:scores => @scores.as_json(:include => {:gsong => { :include => { :song => { :only => [:title, :album]}}, :only => [:artwork]}}, :only => [:song_id, :score]),
}
end
它在功能上运行良好,但它在数据库中进行了太多查询,如下所示:
score Load (0.1ms) SELECT `scores`.* FROM `scores` WHERE `scores`.`user_id` = 3
Gsong Load (0.1ms) SELECT `gsongs`.* FROM `gsongs` WHERE `gsongs`.`id` = 8 LIMIT 1
Song Load (0.1ms) SELECT `songs`.* FROM `songs` WHERE `songs`.`id` = 8 LIMIT 1
Gsong Load (0.1ms) SELECT `gsongs`.* FROM `gsongs` WHERE `gsongs`.`id` = 2 LIMIT 1
Song Load (0.1ms) SELECT `songs`.* FROM `songs` WHERE `songs`.`id` = 2 LIMIT 1
Gsong Load (0.1ms) SELECT `gsongs`.* FROM `gsongs` WHERE `gsongs`.`id` = 1 LIMIT 1
Song Load (0.1ms) SELECT `songs`.* FROM `songs` WHERE `songs`.`id` = 1 LIMIT 1
Gsong Load (0.1ms) SELECT `gsongs`.* FROM `gsongs` WHERE `gsongs`.`id` = 11 LIMIT 1
Song Load (0.1ms) SELECT `songs`.* FROM `songs` WHERE `songs`.`id` = 11 LIMIT 1
Gsong Load (0.1ms) SELECT `gsongs`.* FROM `gsongs` WHERE `gsongs`.`id` = 12 LIMIT 1
Song Load (0.1ms) SELECT `songs`.* FROM `songs` WHERE `songs`.`id` = 12 LIMIT 1
Gsong Load (0.1ms) SELECT `gsongs`.* FROM `gsongs` WHERE `gsongs`.`id` = 23 LIMIT 1
Song Load (0.1ms) SELECT `songs`.* FROM `songs` WHERE `songs`.`id` = 23 LIMIT 1
如何使用单个或两个查询获取所有这些数据,如:
Gsong Load (0.1ms) SELECT `gsongs`.* FROM `gsongs`
Song Load (0.3ms) SELECT `songs`.* FROM `songs` WHERE `songs`.`id` IN (8,2,1,11,12,23)
答案 0 :(得分:0)
我会研究使用ActiveModel序列化程序。我想你会发现它会让复杂的JSON像这样轻而易举地
上有一个很棒的截屏视频