0

请任何人帮助我:

我使用 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)
4

1 回答 1

0

我会考虑使用 ActiveModel 序列化程序。我想你会发现它会让复杂的 JSON 变得轻而易举

有一个很棒的截屏视频

http://railscasts.com/episodes/409-active-model-serializers

于 2013-03-14T15:59:11.713 回答