質問は長くなるかもしれませんが、問題は実際には単純です。リスト、外観、ムービーの 3 つのモデルがあります。List には Appearance を介して多数のムービーがあり、結合モデルの属性ランクによってソートする必要があります。では、どのインデックスを使用すればよいでしょうか? これは私のモデルが現在どのように見えるかです:
# Models
class Movie < ActiveRecord::Base
has_many :appearances, :dependent => :destroy
has_many :lists, :through => :appearances
end
class Appearance < ActiveRecord::Base
belongs_to :list
belongs_to :movie
end
class List < ActiveRecord::Base
has_many :appearances, :dependent => :destroy
has_many :movies, :through => :appearances
def self.find_complete(id)
List.includes({:appearances => :movie}).where("appearances.rank IS NOT NULL").order("appearances.rank ASC").find(id)
end
end
そして、ここに私がすでに持っているインデックスがあります。複合インデックスは必要ですか? それともランク別のインデックスですか?
# Tables
class CreateAppearances < ActiveRecord::Migration
def change
create_table :appearances do |t|
t.integer :list_id, :null => false
t.integer :movie_id, :null => false
t.integer :rank
end
add_index :appearances, :list_id
add_index :appearances, :movie_id
end
end
最後に、その find_complete List メソッドをリファクタリングする方法はありますか? default_scope を使用するのが好きですか? ランクが null になる可能性があることを忘れないでください。