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

时间:2019-01-16 10:45:52

标签: ruby-on-rails postgresql activerecord ruby-on-rails-5 ransack

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

app / models / organization.rb

has_many

使用的迁移:

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 关联,所以这不可能吗?我正在使用PostgreSQL。

1 个答案:

答案 0 :(得分:1)

对于给定的问题,没有超级索引。