创建一个包含 has_many 个关联的索引

Create an index which includes has_many associations

我使用 Ransack 搜索一个 Organization 模型和几个 has_many 模型(大多数是多态的)。

app/models/organization.rb

class Organization < ApplicationRecord
  has_many :phone_numbers, as: :callable, dependent: :destroy
  has_many :addresses, as: :addressable, dependent: :destroy
  has_many :memberships, dependent: :destroy
  has_many :members, through: :memberships, source: :person 

  ransack_alias :ransack_attributes, :name_or_
                                     old_id_or_addresses_line1_or_
                                     addresses_street_or_addresses_zip_code_or_
                                     addresses_city_or_phone_numbers_value_or_
                                     members_first_name_or_
                                     members_last_name_and_slug_and_old_id
  [...]

使用的迁移:

create_table :organizations do |t|
  t.string :name
  t.string :description
end
add_index :organizations, :name

create_table :addresses do |t|
  t.string :line1
  t.string :line2
  t.string :street
  t.string :zip_code
  t.string :city
  t.references :address_type, foreign_key: true
  t.references :addressable, polymorphic: true
end

create_table :phone_numbers do |t|
  t.string :value
  t.references :phone_number_type, foreign_key: true
  t.string :description
  t.references :callable, polymorphic: true
  t.integer :position
end

create_table :memberships do |t|
  t.references :organization, foreign_key: true
  t.references :person, foreign_key: true
  t.references :membership_type, foreign_key: true
  t.string :memo
end

create_table :people do |t|
  t.string :first_name
  t.string :middle_name
  t.string :last_name
  t.date :birthday
  t.string :title
  t.string :gender
end 

在控制器中我搜索 organizations:

@organizations = Organization.ransack(ransack_attributes_cont:params[:q]).
                              result(distinct: true).
                              includes(
                              :addresses
                              ).order(:updated_at).reverse_order

显然搜索速度很慢。所以我正在考虑为每个使用的模型的请求属性创建索引。

def change
  add_index(:addresses, [:line1, :street, :zip_code, :city], name: 'ransack_addresses_index')
  add_index(:organizations, [:name, :old_id, :slug], name: 'ransack_organizations_index')
  add_index(:phone_numbers, [:value])
  add_index(:people, [:first_name, :last_name], name: 'ransack_people_index')
end

但我想知道是否有更好的索引方式? 我可以在所有使用的字段上创建一个超级索引吗 或者这是不可能的,因为它们是多态的 has_many 关联?我正在使用 PostgreSQL。

给定问题没有超级索引。