Rails 注意索引 name

Posted by wxianfeng Thu, 14 Apr 2011 17:56:00 GMT

测试环境:rails 2.X + rails 3.0.3

今天发现 rails api上索引name的命名规则是错误的,here

测试:

ruby-1.9.2-p0 > ActiveRecord::Migration.add_index :users , :email
-- add_index(:users, :email)
  SQL (0.4ms)  SHOW KEYS FROM `users`
  SQL (367.1ms)  CREATE INDEX `index_users_on_email` ON `users` (`email`)
   -> 0.3680s

按照 文档上写的应该是 users_email ,但是实际上是 index_users_on_email

ruby-1.9.2-p0 > ActiveRecord::Migration.add_index :users , :name , :unique=>true
-- add_index(:users, :name, {:unique=>true})
  SQL (0.3ms)  SHOW KEYS FROM `users`
  SQL (340.4ms)  CREATE UNIQUE INDEX `index_users_on_name` ON `users` (`name`)
   -> 0.3413s

按照文档写的应该是 users_name ,但是实际上是 index_users_on_name

ruby-1.9.2-p0 > ActiveRecord::Migration.add_index :users , [:login,:name] 
-- add_index(:users, [:login, :name])
  SQL (0.3ms)  SHOW KEYS FROM `users`
  SQL (314.3ms)  CREATE INDEX `index_users_on_login_and_name` ON `users` (`login`, `name`)
   -> 0.3152s

按照文档下写的应该是 users_login_name 而实际是 index_users_on_login_and_name

为什么 name 如此重要,因为 remove_index 也是根据name 来的,所以 规则必须记住!

例如文档上一个demo:

# Remove the suppliers_name_index in the suppliers table.
#   remove_index :suppliers, :name

其实 是删除 name 为 index_suppliers_on_name 的索引 ,而不是文档上说的 suppliers_name_index

文档上是错误的,从 源码中 也可以看出来

idnex_name method 源码:

 def index_name(table_name, options) #:nodoc:
        if Hash === options # legacy support
          if options[:column]
            "index_#{table_name}_on_#{Array.wrap(options[:column]) * '_and_'}" # HERE
          elsif options[:name]
            options[:name]
          else
            raise ArgumentError, "You must specify the index name"
          end
        else
          index_name(table_name, :column => options)
        end
      end

rails查看 表的索引:

ruby-1.9.2-p0 > ActiveRecord::Migration.indexes("users") # users 是表名

This entry was posted on Thu, 14 Apr 2011 17:56:00 GMT and Posted in . You can follow any any response to this entry through the Atom feed. You can leave a comment or a trackback from your own site.

Tags


Trackbacks

Use the following link to trackback from your own site:
http://wxianfeng.com/trackbacks?article_id=199

Comments

Leave a comment