问题可能很长,但问题其实很简单。我有 3 个模型:列表、外观和电影。一个 List 通过一个 Appearance 有很多 Movies,它们应该按照 joins 模型的属性等级排序。那么我应该使用哪些索引呢?这是我的模型目前的样子:
# 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 一样?不要忘记排名可能为空。