【问题标题】:Creating a table categorization with has_many :through for categories and posts使用 has_many :through 为类别和帖子创建表分类
【发布时间】:2017-12-20 19:20:04
【问题描述】:

嘿,伙计们,我正在做一个 has_many :通过 ruby​​ on rails 中的关联。 如果我的例子没问题,我需要一些帮助。 所以我假装为帖子做分类。 假设我已经建立了班级职位。 因此,为了为类别创建数据库,我假装这样做:

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

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

【问题讨论】:

  • 使用t.belongs_to 定义列将自动为您创建索引。是的,这通常是提高数据库性能的一个好主意。
  • 很好,感谢 XML Slayer 的回复!

标签: ruby-on-rails ruby ruby-on-rails-4 sqlite3-ruby


【解决方案1】:

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

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

有效。 但是它也没有必要,而且性能可能低于您在 product_idcategory_id 上单独定义的单列索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    相关资源
    最近更新 更多