2

I have this for my migration:

class CreateCategories < ActiveRecord::Migration
  def up
    create_table :categories do |t|
      t.integer :parent_id
      t.string  :title, :null => false
    end
    execute('CREATE UNIQUE INDEX ix_categories_root_title ON categories (title) WHERE parent_id IS NULL') 
  end
  def down
    drop_table :categories
  end
end

But when I peeked into db/schema.rb I saw this instead:

ActiveRecord::Schema.define(:version => 20110808161830) do
  create_table "categories", :force => true do |t|
    t.integer "parent_id"
    t.string  "title", :null => false
  end
  add_index "categories", ["title"], :name => "ix_categories_root_title", :unique => true
end

Which obviously isn't the same thing and incorrect. Is there anyway to force schema.rb to create the same index? I'm using postresql with Rails 3.1 pre.

vince
  • 2,374
  • 4
  • 23
  • 39

2 Answers2

3

iafonov was correct when he said to enable this config option in your application.rb file:

config.active_record.schema_format = :sql

However, simply enabling this feature does not work as expected. It will not automatically generate a schema.sql file. Instead you can use rake db:structure:dump which will create a structure.sql file. Then you can load it with rake db:structure:load

There's a nice explanation here: schema.sql not creating even after setting schema_format = :sql

Community
  • 1
  • 1
Andrew
  • 227,796
  • 193
  • 515
  • 708
1

I don't know the exact reason of your problem, but you can definitely store your index if you'll store your schema in sql

config.active_record.schema_format = :sql

Btw: which db do you use? Actually this is more like be problem of db driver than problem of rails.

iafonov
  • 5,152
  • 1
  • 25
  • 21
  • i'm on rails 3.1 pre with postgresql – vince Aug 10 '11 at 16:14
  • Rails supports only basic set of features of database engines, so the only solution is to dump your schema in sql. The only drawback is loosing readable schema but you'll definitely have all your advanced indexes in place. – iafonov Aug 10 '11 at 17:38
  • i'm not able to create the schema in sql even after putting "config.active_record.schema_format = :sql" in application.rb. can someone help? http://stackoverflow.com/questions/7034977/how-to-create-schema-in-sql – vince Aug 14 '11 at 01:04
  • same here, it's still generating a .rb file instead of a .sql file – Andrew Aug 24 '12 at 19:36
  • i think its rake db:schema:dump to generate the sql version – jakeonrails Oct 18 '12 at 23:27
  • nope! it is rake db:structure:dump (http://oomoo.wordpress.com/2008/03/11/migration-related-rake-commands/) – jakeonrails Oct 18 '12 at 23:28