【译】请记得加索引

Sunday, July 25, 2010

原文:http://rails-bestpractices.com/posts/21-always-add-db-index

总是给外键加上索引,这样可以提升sql查询的性能.

丑陋的...

class CreateComments < ActiveRecord::Migration
  def self.up
    create_table "comments", :force => true do |t|
      t.string :content
      t.integer :post_id
      t.integer :user_id
    end
  end

def self.down
    drop_table "comments"
  end
end

默认情况下,rails不会自动给外键加上索引,需要我们自己加上

重构...

class CreateComments < ActiveRecord::Migration
  def self.up
    create_table "comments", :force => true do |t|
     t.string :content
     t.integer :post_id
     t.integer :user_id
    end

    add_index :comments, :post_id
    add_index :comments, :user_id
  end

  def self.down
    drop_table "comments"
  end
end

这是个基本的经验, 请这样做!~你懂的。。。

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top