I have the following situation in production:
My PersonalInfo model was created using t.references :user, foreign_key: true, index: true, unique: true to model Users. However, PersonalInfo became polymorfic, with this migration:
class AddInfoOwnerToPersonalInfos < ActiveRecord::Migration[5.1]
def up
rename_column :personal_infos, :user_id, :info_owner_id
add_column :personal_infos, :info_owner_type, :string
add_index :personal_infos, [ :info_owner_type, :info_owner_id]
PersonalInfo.update_all(info_owner_type: 'User')
change_column :personal_infos, :info_owner_type, :string, null: false
end
def down
rename_column :personal_infos, :info_owner_id, :user_id
remove_column :personal_infos, :info_owner_type
end
end
The problem:
Still remain a fk constraint in database:
ALTER TABLE ONLY public.personal_infos
ADD CONSTRAINT fk_rails_796da13f22 FOREIGN KEY (info_owner_id) REFERENCES public.users(id);
How could I build a migration to remove safely this constraint? (I believe no constraint is needed in polymorphic associations, only the index)
if foreign_key_exists?(:personal_infos, :users)
remove_foreign_key(:personal_infos, :users)
end
See:
Rails API: remove_foreign_key
Related
I was following the tutorial on hackernoon, to generate Obfuscated URLs.
The first step is to add a slug column to the database, but I got an error.
AddSlugToReservations
class AddSlugToReservation < ActiveRecord::Migration[5.2]
def change
add_column :reservations, :slug, :string, null: false
add_index :reservations, :slug, unique: true
end
end
I get the following error when I try rails db:migrate
SQLite3::SQLException: Cannot add a NOT NULL column with default value NULL: ALTER TABLE "reservations" ADD "slug" varchar NOT NULL
So I change the migration file to:
class AddSlugToReservation < ActiveRecord::Migration[5.2]
def change
add_column :reservations, :slug, :string, null: false, default: 0
change_column :reservations, :slug, :string, default: nil
add_index :reservations, :slug, unique: true
end
end
But then I encountered the following error:
SQLite3::ConstraintException: UNIQUE constraint failed: reservations.slug: CREATE UNIQUE INDEX "index_reservations_on_slug" ON "reservations" ("slug")
What should I do? I couldn't find any solution to this...
You can do this with below code
class AddSlugToReservation < ActiveRecord::Migration[5.0]
def change
add_column :reservations, :slug, :string, unique: true, default: 0, null: false
end
end
try this
class AddSlugToReservation < ActiveRecord::Migration[5.2]
def change
add_column :reservations, :slug, :string, unique: true
change_column_null :reservations, :slug, false
end
end
Hope it helps.
Using Postgres as the backing store, I have a table which (at least for the time being) has both an integer primary key and a uuid with a unique index.
It looks something like this in my schema.rb (simplified for example):
create_table "regions", force: cascade do |t|
t.integer "region_id"
t.uuid "uuid", default: "uuid_generate_v4()"
t.string "name"
end
add_index "regions", ["uuid"], name "index_regions_on_uuid", unique: true, using :btree
I then have a table which has a reference to the integer id, something like this:
create_table "sites", force:cascade do
t.integer "site_id"
t.integer "region_id"
t.string "name"
end
What I want to do is to switch from region_id to uuid as the foreign key in the second table. How should I god about writing this migration?
Just create a migration, and inhale some SQL magic into it:
def up
# Create and fill in region_uuid column,
# joining records via still existing region_id column
add_column :sites, :region_uuid
if Site.reflect_on_association(:region).foreign_key == 'region_id'
# We won't use 'joins(:regions)' in case we will need
# to re-run migration later, when we already changed association
# code as suggested below. Specifying join manually instead.
Site.joins("INNER JOIN regions ON site.region_id = regions.id").update_all("region_uuid = regions.uuid")
end
drop_column :sites, :region_id
end
Then you just need to fix your association:
class Site < ActiveRecord::Base
belongs_to :region, primary_key: :uuid, foreign_key: :region_uuid
end
class Region < ActiveRecord::Base
has_many :sites, primary_key: :uuid, foreign_key: :region_uuid
end
From your comment, its seems that you want to modify the primary key referenced by the association, not the foreign key. You actually don't need a migration to do this. Instead, just specify the primary key on the association definitions in each model:
Class Region << ActiveRecord::Base
has_many :sites, primary_key: :uuid
end
Class Site << ActiveRecord::Base
belongs_to :region, primary_key: :uuid
end
The foreign key, since it follows rails convention of being named as the belongs_to relation with an appended "_id" (in this case, region_id), does not need to be specified here.
ETA: You will also need to ensure that the type of sites.region_id matches the type of regions.uuid, which I assume is uuid. I'm also going to assume that this field was previously indexed (under ActiveRecord convention) and that you still want it indexed. You can change all this in a migration like so:
def up
remove_index :sites, :region_id
change_column :sites, :region_id, :uuid
add_index :sites, :region_id
end
def down
remove_index :sites, :region_id
change_column :sites, :region_id, :integer
add_index :sites, :region_id
end
I'm looking for the preferred way, and unique column to an existing table. I also want to add a unique index to the table. Before adding the index though, I obviously need to add data to the column to prevent the index creation from failing.
Here is the situation:
class AddUsernameToUsers < ActiveRecord::Migration
def change
add_column :users, :username, :string, null: false
# Need Data here! And don't want to do something like this:
# User.each { |u| u.update_attribute(:username, u.email }
add_index :users, :username, unique: true
end
end
I know using ruby code to populate the data is possible, there are lots of examples of that, but I keep reading that it isn't such a good idea. Are there any options other than something similar to the above?
would the following work for your situation?
class AddUsernameToUsers < ActiveRecord::Migration
def change
add_column :users, :username, :string, null: true
execute("UPDATE users SET username = email")
change_column :users, :username, :string, null: false
add_index :users, :username, unique: true
end
end
I have a migration that I want to make with a reference in my table. I create the reference using this:
create_table :user_events do |t|
t.references :user, :null => false
end
And in my migration, I want to be able to allow the reference to be NULL.
def self.up
change_column :user_events, :user, :integer, :null => true
end
However I keep getting PGError: ERROR: column "user" of relation "user_events" does not exist. Am I migrating wrong?
This should work:
def self.up
change_column :user_events, :user_id, :integer, :null => true
end
Note that the column you're trying to change is called user_id, not user
It's because your migration creates a column named user_id, referencing the User model.
try
def self.up
change_column :user_events do |c|
c.references :user, :integer, :null => true
end
end
I have the following two migrations already in my database:
When I created Prices:
class CreatePrices < ActiveRecord::Migration
def self.up
create_table :prices do |t|
t.string :price_name
t.decimal :price
t.date :date
t.timestamps
end
# add_index :prices (not added)
end
def self.down
drop_table :prices
end
end
and when I added a user_id to Prices:
class AddUserIdToPrices < ActiveRecord::Migration
def self.up
add_column :prices, :user_id, :integer
end
# add_index :user_id (not added)
end
def self.down
remove_column :prices, :user_id
end
end
Is there a way from the command line to add prices and user_id to index? I looked at this question and still was confused on how to go about adding indexes and the parts where I put "not added" seem like they would be error-prone because they were earlier migrations.
My question is, what is the best way for me to add indexing to prices and user_id?
Thank you for the help!
I think one extra migration fits well:
class AddIndexes < ActiveRecord::Migration
def self.up
add_index :prices, :user_id
add_index :prices, :price
end
def self.down
remove_index :prices, :user_id
remove_index :prices, :price
end
end
Or you can use change syntax with newer versions of rails, look at DonamiteIsTnt comment for details:
class AddIndexes < ActiveRecord::Migration
def change
add_index :prices, :user_id
add_index :prices, :price
end
end
Once an app is in production, the intent is that migrations will be applied once.
If you're still developing your app, you can always add them as you've noted followed by a rake db:migrate:reset this will wipe your database and re-create it.
Otherwise, create a new migration rails g migration add_user_id_index.
class AddUserIdIndex < ActiveRecord::Migration
def self.up
add_index :prices, :user_id
end
def self.down
remove_index :prices, :user_id
end
end
FWIW, add_index :prices doesn't make sense. Indexes are per-column, not per-table.
You can always manually create indexes by logging into your database.
CREATE INDEX prices__user_id__idx ON prices (user_id);
Simple solution:
create a new migration
add the indexes there (they don't need to be in the older migrations)
run the migrations