2018-08-08

2018-08-17  本文已影响0人  陈华萍

建立索引的两种写法

第一种:

def change

    create_table :booksdo|t|

        t.belongs_to :author, index: true

        t.datetime :published_at

        t.timestamps

      end

end

第二种:

  def change

    create_table :accounts do |t|

      t.integer :supplier_id

      t.string  :account_number

      t.timestamps

    end

    add_index :accounts, :supplier_id

  end

案例2

多态关联

classPicture < ApplicationRecord

  belongs_to :imageable, polymorphic: true

end

classEmployee < ApplicationRecord

  has_many :pictures, as: :imageable

end

classProduct < ApplicationRecord

  has_many :pictures, as: :imageable

end

写法1:

  def change

    create_table :pictures do |t|

      t.string  :name

      t.integer :imageable_id

      t.string  :imageable_type

      t.timestamps

    end

    add_index :pictures, [:imageable_type, :imageable_id]

  end

写法2:

  def change

    create_table :pictures do |t|

      t.string :name

      t.references :imageable, polymorphic: true, index: true

      t.timestamps

    end

  end

自连接:

model:

class Employee < ApplicationRecord

  has_many :subordinates, class_name: "Employee",

                          foreign_key: "manager_id"

  belongs_to :manager, class_name: "Employee"

end

迁移:

class CreateEmployees < ActiveRecord::Migration[5.0]

  defchange

    create_table :employeesdo|t|

      t.references :manager, index: true

      t.timestamps

    end

  end

end

上一篇 下一篇

猜你喜欢

热点阅读