誰か助けてください:
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
次のような 1 つまたは 2 つのクエリを使用して、このすべてのデータを取得するにはどうすればよいですか。
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)