這個問題可能很長,但問題其實很簡單。我有3個模型:列表,外觀和電影。列表通過外觀具有許多電影,並且它們應該按照聯合模型的屬性等級進行排序。那麼我應該使用哪些索引?這是我的模型目前的樣子:當查詢結果按has_many排序時,應該使用什麼索引:through association
# 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一樣?不要忘記,排名可能爲空。
事實上,你是對的,它正在做兩個查詢。我想我應該在我的問題中解釋我正在使用PostgreSQL。我要去嘗試你的解決方案。 – Ashitaka