使用has_many创建表分类:through用于类别和帖子

问题描述 投票:1回答:1

嘿伙计们,我正在做一个has_many:通过在轨道上的ruby中的关联。如果我的例子没问题,我想要一些帮助。所以我假装为帖子做类别。假设我已经建立了课程帖子。因此,为了创建类别的数据库,我假装这样做:

class CreateCategories < ActiveRecord::Migration[5.0]
  def change
    create_table :categories do |t|
      t.string :name
      t.timestamps
    end
  end

  def change
    create_table :categorizations do |t|
      t.belongs_to :post, index: true
      t.belongs_to :category, index: true
      t.integer :position

      t.timestamps
    end

    add_index :categorizations, [:product_id, :category_id], unique: true
  end
end

这些索引可以提升数据库吗?

ruby-on-rails ruby ruby-on-rails-4 sqlite3-ruby
1个回答
1
投票

是的,您在底部定义的多列索引:

add_index :categorizations, [:product_id, :category_id], unique: true

已验证。但是,与在product_idcategory_id上单独定义的单列索引相比,它也是不必要的,并且可能性能较差。

© www.soinside.com 2019 - 2024. All rights reserved.