Rails 3 Migration screw ups - ruby-on-rails-3

I recently added Devise and CanCan to my Rails 3.2.3 app and need to run rake db:migrate in order to get them working properly. I have a migration file for links that I created already and it is somehow conflicting with when I run rake db:migrate
== CreateLinks: migrating ====================================================
-- create_table(:links)
rake aborted!
An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "links" already exists: CREATE TABLE "links" ("id"INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "url" varchar(255), "description" var
char(255), "created_at" datetime NOT NULL, "points" integer, "updated_at" dateti
me NOT NULL)
I tried running rake db:migrate:reset but this seems to do nothing to help my situation. I still cant run a db migration for my new gems. How can I get around this? Can I omit the links migration somehow?

sDid you create the links table manually before running the migration? Somehow you seem to have gotten your migrations out of sync with your database.
If you are not concerned about any of the data in the database, you can do a rake db:drop first, then do the rake db:migrate. This blows away all the tables in the database and run all the migrations again from the beginning.
If you do need to maintain the existing database tables, then you could wrap the create_table :links statement with an unless table_exists? :links statement.

Related

PG::UniqueViolation error even when there is no duplicate key value. How to resolve this issue?

I have a table called comms_applications and in my table i have an index
add_index "comms_applications", ["user_id", "gender", "deleted_at"], name: "index_comms_application_user_gender_active", using: :btree
I am certain i do not have a duplicate key value but i keep getting this error message when i try to update my table
error: PG::UniqueViolation: ERROR: duplicate key value violates
unique constraint
"index_comms_applications_on_user_id_and_gender"\nDETAIL: Key
(user_id, gender)=(629, Female)
I tried dropping the index but still the error is still showing.
Is there a way for me to remove all data stored in an index for postgresql or anyway i can resolve this issue.
I am using Rails 4 with Postgres 11
I think this can also resolve your problem, Add this in your staging or preprod console ( I am using Heroku for this so I added in my heroku rails console)
connection = ActiveRecord::Base.connection
connection.execute("SELECT setval(pg_get_serial_sequence('comms_applications', 'id'), MAX(id)) FROM comms_applications;")
Check out this blog for more info and how this is been generated

Sequelize: How to undo migrations for dropped tables?

In my Express Sequelize Postgres app, I created a migration to create a model/table with some attributes.
After the migration (status: up), I dropped the table.
Now I cannot undo the migration - the migration file exists, but I get the following error:
ERROR: relation "public.CustomerAddresses" does not exist
How do I undo the migration, so I can remigrate?
Here are two possible options:
As mentioned, you can undo your manual drop by manually recreating the table. As long as the table exists, you'll be able to undo your migration.
You can remove the entry for your migration from the migrations table to make the state of your schema match the state of the migrations table, since you've already performed the drop manually:
DELETE FROM "SequelizeMeta" WHERE name='<your migration name>';

rails 3.0.12 how to check what version of activerecord do i have?

Maybe it's a silly question but I need multiple primary keys in some tables something like...
create table t1
(
id int not null
id_something int not null
.
.
.
primary key (id, id_something)
)
I googled and I found this gem http://rubygems.org/gems/composite_primary_keys
but I couldn't find what activerecord version do I have
I'm using rails 3.0.12 and ruby 1.9.2p320
Run bundle show activerecord at the terminal.
Run bundle info activerecord in your terminal
As bundle show activerecord
is deprecated in some of the rails versions.

Rails seed: How to truncate DB table?

Before seeding test data into DB table I need to truncate the table (I need to reset primary key), I am trying to do that this way:
ActiveRecord::Base.connection.execute("TRUNCATE users")
but when I print out data from DB, I still don't see counting primary key from 1.
What am I doing wrong?
EDIT:
Also, I've tried manually run in terminal to PostgreSQL database
truncate users
But the primary count still doesn't start from 1.
SOLUTION:
In Postgres, run:
ALTER SEQUENCE users_id_seq RESTART WITH 1;
In MySQL, TRUNCATE table; deletes all rows and resets the auto increment counter.
In PostgreSQL it does not do this automatically. You can use TRUNCATE TABLE table RESTART IDENTITY;.
Just for the record: In SQLite, there is no TRUNCATE statement, instead, it's
DELETE FROM table;
DELETE FROM sqlite_sequence WHERE name='table';
In case your db is postgres, you can do something like this to truncate the db tables of your models:
[
MyModel1,
MyModel2,
MyModel3
].each do |m|
ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{m.table_name} RESTART IDENTITY;")
end
This is too late I'm answering this question but I hope this will help someone else.
You've to install (OR you can add gem 'database_cleaner' to your Gemfile) a GEM called Database Cleaner which helps to clean your database without affecting your database schema._
To clean your database each time whenever you do rake db:seed then paste
DatabaseCleaner.clean_with(:truncation)
on the top of your seed file. It'll clear your database and start count from 1 again.
Disclaimer : This updated answer is tested, and working perfectly in my system.
From within Rails in a csv_upload.rb I used and it worked.
ActiveRecord::Base.connection.execute('TRUNCATE model_name RESTART IDENTITY')

Generate Rails migrations from a schema

I am creating a new Rails application which will work with an existing schema. I have been given the schema SQL but I want to create Rails migrations to populate the database in development. The schema is not overly complicated, with around 20 tables, however I don't want to waste time and risk typos by manually creating the migrations.
Is there a way to generate Rails migrations given a schema's SQL?
Sure, connect your application to your database, then run
rake db:schema:dump
This will give you a db/schema.rb ready with all of your definitions. Now that you have that db/schema.rb, simply copy the contents within the declaration into a new migration. I've done this before, and it works just great.
I prefer to simply write the initial migration's up method with SQL execute calls:
class InitialDbStructure < ActiveRecord::Migration
def up
execute "CREATE TABLE abouts (
id INTEGER UNSIGNED AUTO_INCREMENT,
updated_at TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
created_at TIMESTAMP,
title VARCHAR(125),
body MEDIUMTEXT,
CONSTRAINT PK_id PRIMARY KEY (id),
INDEX ORDER_id (id ASC)
) ENGINE=InnoDB;"
end
NOTES
You will find, particularly if you are often rebuilding and repopulating tables (rake db:drop db:create db:schema:load db:fixtures:load), that execute statements run far faster than interpreted Ruby syntax. For example, it takes over 55 seconds for our tables to rebuild from Rails migrations in Ruby syntax, whereas execute statements re-generate and re-populate our tables in 20 seconds. This of course is a substantial issue in projects where initial content is regularly revised, or table specifications are regularly revised.
Perhaps of equal importance, you can retain this rebuild and repopulate speed by maintaining a single original migration in executed SQL syntax and re-executing migrations (of that single file) by first gutting your schema.rb and then running rake db:reset before re-populating your tables. Make sure you set :version => 0, so that you will get a new schema, faithful to your migration:
ActiveRecord::Schema.define(:version => 0) do
end