Problems with rake db:migrate - ruby-on-rails

First
ruby script/generate model Buyer id:integer name:string
after generating Buyer model, I did
rake db:migrate
it was working fine.
After 1 day I have executed below command
ruby script/generate model Seller id:integer seller_name:string
after generating Seller model, I did
rake db:migrate
I got an error, that Buyer table is already exists. why? we have different timestamp file.
class CreateBuyer < ActiveRecord::Migration
def self.up
create_table :buyer do |t|
t.string :name
t.text :description
t.decimal :price
t.integer :seller_id
t.string :email
t.string :img_url
t.timestamps
end
end
def self.down
drop_table :ads
end
end
and another one is
class CreateSellers < ActiveRecord::Migration
def self.up
create_table :sellers do |t|
t.integer :nos
t.decimal :tsv
t.decimal :avg_price
t.timestamps
end
end
def self.down
drop_table :sellers
end
end
I used Rails 2.3.11 and rake 0.8.7

Are you sure there were no errors generated when you ran the first migration? If an error is encountered while running a migration, the parts that were already run will still be in the database, but schema_migrations won't be updated with the migration timestamp. Therefore, the next time you try to run migrations, it'll try to re-run the first part of the failed migration, which will generate errors since it's already been run.
Updated: If you look in the error output you added (by the way, please add to the question rather than a comment, so it's formatted and the whole thing is included) you can see that the first Execute db:migrate is running the migration CreateBuyer. This confirms that your migration did not complete the first time you ran it or has since been unsuccessfully rolled back. To fix this, manually drop the buyer table, then rerun your migrations.
As a note, there's at least a couple issues in your CreateBuyers migration:
The table name should be buyers (plural) rather than buyer (singular)
The down part of the migration is dropping the table ads instead of buyers
The second problem there could explain why you're having trouble running migrations now, actually. If you rolled back the CreateBuyers migration, it would have dropped your ads table and left buyers in place.

Related

How to Delete Table from Database permanently in ROR

I've generated a scaffold and then migrated my database. After that, I destroyed my scaffolding and then generated scaffold again and try to migrate my database but I got an error that this table already exists. How can I delete that table from the database?
One other easy way to do so :
open rails console and use this command :
ActiveRecord::Migration.drop_table(:your_table_name)
If you haven't pushed your code then the solution given by #Cryptex Technologies works fine. But if you have(i.e if you are using version control) then i won't recommend that approach. In that case you should create a new migration something like this:
class RemoveTable < ActiveRecord::Migration[5.2]
def up
drop_table :table_name
end
def down
create_table :table_name do |t|
t.string :field_name_1
t.text :field_name_2
t.timestamps
end
add_index :table_name, :field_name_1, unique: true
end
end
To delete that table, you need to run the command
rake db:rollback
and if you want to delete the database of your current application.
then you need to run the command
rake db:drop.
Rails automatically generates migration, thanks to the command line generator.
For instance, if you want to remove the Users Table write a command line statement like this:
rails generate migration DropUsersTable
This will generate the empty .rb file in /db/migrate/ that still needs to be filled to drop the “Users” table in this case.
A Quick-and-Dirty™ implementation would look like this:
class DropUsersTable < ActiveRecord::Migration
def up
drop_table :users
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
It’s “correct” as it shows that the migration is one-way only and should not/can not be reversed. But in order to make a truly clean job in case these modifications were to be reversed we need to have a symmetrical migration (assuming we could recover the lost data), which we can do by declaring all the fields of our table in the migration file:
class Dropusers < ActiveRecord::Migration
def change
drop_table :users do |t|
t.string :name, null: false
t.timestamps null: false
end
end
end
This can be long if the model is complex, but it ensures full reversibility.
Here again, changes will enter effect as usual after running rake db:migrate.

Ruby on Rails does not generate foreign key from association

I have two set up two database tables called 'points' and 'activities'. I want to give the table 'points' a foreign key 'activity_id' by setting up the associations as follows:
class Activity < ActiveRecord::Base
belongs_to :user
has_many :points, dependent: :destroy
...
end
and
class Point < ActiveRecord::Base
belongs_to :activity
end
In addition, I have the following migrations file for creating the points table:
class CreatePoints < ActiveRecord::Migration
def change
create_table :points do |t|
t.integer :activity_id
t.timestamps null: false
t.boolean :activities_completed, array: true, default: []
t.integer :point_value
t.float :time_left
end
end
end
However, when I run
rake db:reset
rake db:migrate
rake db:seed
and then check the the table points by
rails c
Point.column_names
then the foreign key is missing:
irb(main):001:0> Point.column_names
=> ["id", "created_at", "updated_at", "activities_completed", "point_value", "time_left"]
What am I doing wrong? What can I do to make the foreign key activity_id a column of the points table?
I am new to Ruby and Rails. My Rails version is 4.24. Any help is appreciated.
Your create table migration should have a "t.belongs_to :activity, index: true" instead of creating the field activity_id with type integer.
You should have done something like this to add activity_id to your points table.
t.references :activity, index: true, foreign_key: true
#this would have created activity_id column in points
Since now, you have already created your migrations and ran rake db:migrate, learn to remove a column from a table. You need to write migrations to remove activity_id from your points table and add it again.
rails generate migration RemoveActivityIdFromPoints activity_id:integer
rails g migration AddActivityRefToPoints activity:references
These two should create proper migrations for you. Check your migrations folder for confirmation that everything went well, and run rake db:migrate and test again.
Follow this link to learn more about it. http://guides.rubyonrails.org/active_record_migrations.html
I discovered that there was a more fundamental problem. The migration script was not being executed during rake db:migrate. Therefore the changes I had made to the migration were ineffective. I therefore had to use
rake db:migrate:redo VERSION=20160605234351
When I ran this command, then the foreign key appeared.

Adding a column to an existing table

I used following code to add a field director to an existing movies table:
class CreateMovies < ActiveRecord::Migration
def up
create_table :movies do |t|
t.string :title
t.string :rating
t.text :description
t.datetime :release_date
# Add fields that let Rails automatically keep track
# of when movies are added or modified:
t.timestamps
end
add_column :movies, :director, :string
end
def down
drop_table :movies
end
end
I have already seen this, but the difrence is I am insisting to use
rake db:test:prepare command after i add my new field.
when i run rake db:test:prepare and then i run my cucumber, it gives me the erorr:
unknown attribute 'director' for Movie. (ActiveRecord::UnknownAttributeError)
this means that i failed to add the field director to the table movies,
So what is wrong here?
Try the following code:
rails g migration AddDirector
then, in the corresponding migration
def change
add_column :movies, :director, :string
end
Execute , rake db:migrate
In the Movies controller, add "director" in the movie_params
The db:test:prepare recreates the db using the db/schema.rb.
This will fix your issue:
bin/rake db:rollback
bin/rake db:migrate
When you do any migration, it gets saved in schema
Rollback that migration, make changes and then migrate it again
If for example 20150923000732_create_movies.rb migration is your last migration you can rollback with:
rake db:rollback
Otherwise you can simply down your specific migration with VERSION:
rake db:migrate:down VERSION=20150923000732
After rollback your migration, change your migration file and migrate again.

PG::UndefinedTable: ERROR: table "freqs" does not exist

In my db folder, I have two migrations that have do do with this. The first is a migration I created to drop a database I made earlier that did not have what I needed.
class DropProductsTable < ActiveRecord::Migration
def up
drop_table :freqs
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
The second is the new database I created.
class CreateFreqs < ActiveRecord::Migration
def change
create_table :freqs do |t|
t.string :description
t.timestamps
end
end
end
The rake db:migrate works for development, but when I try to migrate Heroku, the error provided in the title occurs. What's happening? I have searched around StackOverflow to no avail.
First, "to drop a database" - not database, but table you mean, right?
Then, it's obvious that this table doesn't exist on Heroku. Try to skip first migration and migrate only second.

Migration issue in Ruby-on-rails

Hey guys, when I first begin a rails project, the model user was designed and created. After all the migration part, it successful created the table "users" at postgres.
Well, then after doing some changes during the project, I realized that was missing an attribute/new column at the table.
So what I did was delete the table users from postgres and add a new column at my first migration ruby class:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
t.string :password
t.string :email
t.string :authorization_token //this is the new attribute that I insert
t.datetime :created_at
t.datetime :updated_at
t.timestamps
end
end
def self.down
drop_table :users
end
end
So, when I run again the db:migrate hopping that a new user table will be created with the new attribute :authorization_token, it doesn't work, but with no errors.
(I know that I should not remove the table, there is another smart way to do it)
A tip for working with Rails -- do not hand modify your tables using SQL. When you saw the problem you should have written a new migration like #nruth showed. Running the rake:migrate command would have worked fine for you.
In this case since you've already deleted your 'users' table you now have the problem that your database schema is out of sync with what Rails thinks it is. To fix this problem you can either get the database schema to roughly match what Rails thinks it is by hand creating the 'users' table, running the down migration and then then the up migration. Or you can get Rails up to speed with the fact that the 'users' table no longer exists. Rails stores migration info in either a schema_info table (Rails < 2.1) or schema_migrations table (Rails >= 2.1). If you remove that table then Rails will think the schema does not exist and try to run all the up migrations and recreate the 'users' table for you again.
Lastly, over time you may accumulate a number of migrations that individually add a column or two that you forgot to include. If you haven't yet shipped or aren't in production yet, then you can write a migration that sort of baselines your table. It would look something like this:
class CreateBaselineUsers < ActiveRecord::Migration
def self.up
create_table :users, :force => true do |t|
t.string :name
...
This will forcibly drop the table and recreate it with all the attributes that you want.
Migrations are run once & stored in the database as having been used (take a look in the schema_migrations table). You could try using rake db:migrate:reset to re-run your initial migration, but it's better to just add new migrations (you won't want to blow away your database when it has data in it) as follows:
script/generate migration add_authorization_token_to_users authorization_token:string
which will generate something similar to the following:
class AddAuthorizationTokenToUsers < ActiveRecord::Migration
def self.up
change_table :users do |t|
t.string :authorization_token //this is the new attribute that I insert
end
end
def self.down
remove_column :users, :authorization_token
end
end
To see how add/remove column, change_table, etc work, take a look at ActiveRecord::ConnectionAdapters::SchemaStatements at http://api.rubyonrails.org or http://guides.rubyonrails.org/migrations.html

Resources