It is a Ruby representation of your database; schema. rb is created by inspecting the database and expressing its structure using Ruby.
The schema. rb serves mainly two purposes: It documents the final current state of the database schema. Often, especially when you have more than a couple of migrations, it's hard to deduce the schema just from the migrations alone. With a present schema.
If you run a rake -T
it will list all possible rake tasks for your Rails project. One of them is db:schema:dump which will recreate the schema.rb for the Rails app from the database.
bundle exec rake db:schema:dump
Careful,
rake db:schema:dump
will dump the current DB schema FROM the DB. This means that if you made any changes to your migrations, they will NOT be reflected in schema.rb file which is not what you want IMO.
If you want to re-create the schema from the migrations, do the following:
rake db:drop # ERASES THE DATABASE !!!!
rake db:create
rake db:migrate
rake db:schema:dump
I think this is still valid in Rails 3 - it regenerates the schema.rb from the database.
RAILS 5 Way:
rails db:schema:dump
or if you Encounter Gem::LoadError then:
bundle exec rails db:schema:dump
Note:
in rails 5 it is recommended that task are generated/executed by using rails
instead of rake
, this is just to remember, rails generated task are of extension .rake
see in lib/tasks/myTask.rake
. which means these task can also be executed by prepending rake
.
If you regenerate schema.rb
locally, you should be alright. It simply holds a representation of the structure of your database tables. The data itself is not contained in this file.
To regenerate your schema.rb
file, run:
bundle exec rake db:schema:dump
Then simply commit the new schema.rb
file and you should be in good shape!
Directly from the schema.rb file itself:
If you need to create the application database on another system, you should be using
db:schema:load
, not running all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations you'll amass, the slower it'll run and the greater likelihood for issues).
So do NOT do the suggestion of rake db:migrate
, which was suggested in the - at the time of this writing - lowest rated answer.
I also had a similar problem where my old schema was not refreshing even if I deleted migration.
So, what I did was dropping all existing tables in the database and migrating them again. Then running "db:schema:load" command gave me a fresh schema.rb.
drop table my_table_name // deleted them individually
rake db:migrate
rake db:schema:dump // re-created a new schema
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With