I am new to rails.
I want to create an Article model. So I run,
rails g model Article name:string context:string
Instead of content I type in context, Is there a way to update the schema.rb file that gets generated?
I would like the articles table to have name and content columns.
Don't focus on schema.rb -- this is just a dump of the current state of your database. Instead, what you need to do is correct the migration file. It is the migration files that actually define what tables/column will exist in production in the end so they must be correct. I'd recommend:
Run ls -ltr db/migrate -- use this to find your migration file and copy the date string. Rails uses this as the "version" of the migration. For example: "20140809165359_create_articles", the version is "20140809165359".
Run bundle exec rake db:migrate:down VERSION=20140809165359 (replace the version number with your own, here)
Now go fix your migration file (change "context" to "content")
Run bundle exec rake db:migrate to migrate back up.
This will fix the underlying problem and you'll notice that now, after migrating back up, your schema.rb will be fixed too.
Related
I am trying to find the correct (any) method to create an application in Ruby on Rails having an existing database (PostgreSQL) with data and fresh app made with:
rails new --database=postgresql -J --skip-coffee .
I found https://github.com/frenesim/schema_to_scaffold but first I need to have a file with a database structure: schema.rb. I’m looking for a way to do it automatically.
In result of rake db:schema:dumpfile schema.rb is generated, but only with content like that:
ActiveRecord::Schema.define(version: 0) do
enable_extension "plpgsql"
end
And I stuck here. Why that file is empty? Why are there no tables here?
I have a connection with DB and no errors. I did rake db:create before to test. Creation of bases described in database.yml is successful.
At the beginning I used Docker containers and this is my goal. But to exclude the probability of error, I installed the environment in the system (macOS Mojave) based on the socket. And I’ve got the same effect.
How to generate schema.rb with structure of existing database? Or is there different way to build RoR app based on the existing data structure?
Update: Connection with the new database I only did for testing purposes. To verify configuration.
Here's what else I did:
Dump existing structure with
pg_dump --schema-only app_development > db/structure.sql
I changed name in database.yml to have fresh place to import.
rake db:setup created new DB
rake db:structure:load create tables from db/structure.sql file in DB correctly.
But rake db:schema:dump still generate empty file as earlier.
If you have set proper db config you can use rake db:migrate to regenerate the schema file.
edit:
Ok so lets check if I understood correctly:
you have an existing db with tables and data in it
you have brand new rails app
you want to reflect db structure in you schema.rb file
Is that correct? If yes then like I wrote before - without adding any new migrations to your codebase, run rake db:migrate. That task not only applies changes from the migration file but also updates your schema file to be in sync with the actual database.
I've got it! Two days of my life.
File used to import PostgreSQL database has at the beginning:
CREATE SCHEMA employees;
-- and later
CREATE TABLE employees.department;
I thought that since Rails generates database by rake db:structure:load , the file's syntax is correct.
But when I create manually table users in new empty database and then pg_dump that new base I don't have CREATE SCHEMA query there.
And finally rake db:schema:dump fills schema.rb with tables as I want:
create_table "users", id: :serial, force: :cascade do |t|
t.text "name"
end
Because that fresh pg_dumped file has CREATE TABLE public.users query. public.
I think the key is in comments in database.yml file:
# Schema search path. The server defaults to $user,public
#schema_search_path: myapp,sharedapp,public
One picture is more valuable than a thousand words: that's the differences Table users on the right goes to schema.rb after rake db:schema:dump
Thanks guys for the comments. It's made sure me that I do not make a terrible mistake.
It sounds like you did rake db:create which creates a new database for you and then did rake db:schema:dump which generated a schema.rb file for you from the newly created (empty) database.
If you have an existing database that you want to use you will need to modify your database.yml file to connect to it.
If you want to create a new database you will need to generate Active Record database migrations e.g.) rails generate migration CreateProducts name:string part_number:string and then run them rake db:migrate to update your database and generate your schema.rb.
When working on a project, I keep track of all the changes I make to a database in a notepad file. Then, later, I manually write all the changes in rails' db migration file.
But it should be possible to compare the schema of a backup of my database, with the new version of my database, and automatically detect the differences. And generate the rails db migration file automatically.
Is there a tool that can compare two database schema's and automatically generate rails' db migration files?
As far as I'm aware, there's no tool that will do it automatically, however, you can get most of the way there just using rake db:schema:dump with source control.
Create a new Rails project and do the following:
Update database.yml to connect to your first database.
Use rake db:schema:dump to populate schema.rb and commit schema.rb to git.
Update database.yml to connect to your second database and again run rake db:schema:dump
Use git diff on schema.rb to compare the changes. This can easily be mapped to a migration.
The benefit of using source control is that you can then test the migration by comparing schema.rb after the migration runs to the schema dump of the second database.
I am trying to create all my tables from schema.rb
I used the command: "rake db:schema:load"
However, this fails because in one of my initializers, it is referencing a model/table that obviously doesn't exist (since the database is empty)
I could comment out these lines, and then run schema:load again, but is there an alternative?
Probably the fastest way is to just move the offending initializer to a temporary directory that is outside of the app, and then run your schema load. But if that doesn't work, or isn't an option for some reason, you could always work around that by creating a bare bones rails app to do the schema load:
Create a new rails app: rails new (app)-fixer
Copy your gemfile (unless there are specific exceptions) to the fixer app.
Copy your database.yml config to the fixer app.
Copy your schema.rb file to the fixer app.
Do all appropriate "bundle install" commands as needed for your app.
Then run "rake db:drop db:create db:schema:load"
That will build up a new database from scratch, based on your current schema.
You can add a check for the table existance in your initializer.
if TheModel.table_exists?
// do something with the model
end
I have a migration with version number 20120926232105. My schema is at version 20121003190827.
My site is hosted on Heroku, and when I run
heroku run rake db:migrate -a my-app
I get an error that the table it is trying to create in migration 20120926232105 already exists (as it should). I don't get it - isn't the whole point of the schema_migration table to record which was the last successful migration?
This guy explains it pretty well.
Basically, there's a table somewhere called "schema_migrations". Your migration's "version number" is actually just a time stamp. Further, there's no record of a migration with that timestamp in your 'schema_migrations' table. Since the migration exists, and its timestamp wasn't found in the 'schema_migrations' table, Rake knows to run it.
Try grep -r "table_name" db/migrate and see if it's in there twice.
Is there an easy way to run a single migration? I don't want to migrate to a certain version I just want to run a specific one.
Assuming fairly recent version of Rails you can always run:
rake db:migrate:up VERSION=20090408054532
Where version is the timestamp in the filename of the migration.
Edit: At some point over the last 8 years (I'm not sure what version) Rails added checks that prevent this from running if it has already been run. This is indicated by an entry in the schema_migrations table. To re-run it, simply execute rake db:migrate:redo VERSION=20090408054532 instead.
You can just run the code directly out of the ruby file:
rails console
>> require "db/migrate/20090408054532_add_foos.rb"
>> AddFoos.new.up
Note: Very old versions of rails may require AddFoos.up rather than AddFoos.new.up.
An alternative way (without IRB) which relies on the fact that require returns an array of class names:
script/runner 'require("db/migrate/20090408054532_add_foos.rb").first.constantize.up'
Note that if you do this, it won't update the schema_migrations table, but it seems like that's what you want anyway.
Additionally, if it can't find the file you may need to use require("./db/..." or try require_relative depending on your working directory
If you want to run a specific migration, do
$ rake db:migrate:up VERSION=20080906120000
If you want to run migrations multiple times, do
# use the STEP parameter if you need to go more than one version back
$ rake db:migrate:redo STEP=3
If you want to run a single migration multiple times, do
# this is super useful
$ rake db:migrate:redo VERSION=20080906120000
(you can find the version number in the filename of your migration)
Edit: You can also simply rename your migration file, Eg:
20151013131830_my_migration.rb -> 20151013131831_my_migration.rb
Then migrate normally, this will treat the migration as a new one (usefull if you want to migrate on a remote environment (such as staging) on which you have less control.
Edit 2: You can also just nuke the migration entry in the database. Eg:
rails_c> q = "delete from schema_migrations where version = '20151013131830'"
rails_c> ActiveRecord::Base.connection.execute(q)
rake db:migrate will then rerun the up method of the nuked migrations.
If you've implemented a change method like this:
class AddPartNumberToProducts < ActiveRecord::Migration
def change
add_column :products, :part_number, :string
end
end
You can create an instance of the migration and run migrate(:up) or migrate(:down) on an instance, like this:
$ rails console
>> require "db/migrate/20090408054532_add_part_number_to_products.rb"
>> AddPartNumberToProducts.new.migrate(:down)
This are the steps to run again this migration file "20150927161307_create_users.rb"
Run the console mode. (rails c)
Copy and past the class which is in that file to the console.
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps null: false end
end
end
end
Create an instance of the class CreateUsers: c1 = CreateUsers.new
Execute the method change of that instance: c1.change
As of rails 5 you can also use rails instead of rake
Rails 3 - 4
# < rails-5.0
rake db:migrate:up VERSION=20160920130051
Rails 5
# >= rails-5.0
rake db:migrate:up VERSION=20160920130051
# or
rails db:migrate:up VERSION=20160920130051
If you're having trouble with paths you can use
require Rails.root + 'db/migrate/20090408054532_add_foos.rb'
If you want to run it from console, this is what you are looking for:
$ rails console
irb(main)> require "#{Rails.root.to_s}/db/migrate/XXXXX_my_migration.rb"
irb(main)> AddFoo.migrate(:up)
I tried the other answers, but requiring without Rails.root didnt work for me.
Also, .migrate(:up) part forces the migration to rerun regardless if it has already run or not. This is useful for when you already ran a migration, have kinda undone it by messing around with the db and want a quick solution to have it up again.
Method 1 :
rake db:migrate:up VERSION=20080906120000
Method 2:
In Rails Console
1. Copy paste the migration class in console (say add_name_to_user.rb)
2. Then in console, type the following
Sharding.run_on_all_shards{AddNameToUser.up}
It is done!!
Please notice that instead of script/runner, you may have to use rails runner on new rails environments.
Looks like at least in the latest Rails release (5.2 at the time of writing) there is one more way of filtering the migrations being ran. One can pass a filter in a SCOPE environment variable which would be then used to select migration files.
Assuming you have two migration files 1_add_foos.rb and 2_add_foos.run_this_one.rb running
SCOPE=run_this_one rails db:migrate:up
will select and run only 2_add_foos.run_this_one.rb. Keep in mind that all migration files matching the scope will be ran.