I currently have the migrate thing like:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.string :encrypted_password
t.string :salt
t.timestamps
end
end
end
now, if I wanna add two new attributes into this file, one is: t.string :type , and the other one is: t.string :memory_token , how can I do this please?
If you have already run the migration you will have to create a new one.
rails g migration AddTypeToUsers
And then in the migration file you can edit in
change_table :users do |t|
t.string :type
t.string :memory_token
end
Then run a migration rake db:migrate to make the changes
If you haven't run the migration then you can simply add
t.string :type
t.string :memory_token
To that file you have showed us and then run your migration
+1 to #JTG
You can also make this just with one line:
rails g migration AddTypeAndMemoryTokenToUsers type:string memory_token:string
and you will get a following file:
class AddTypeAndMemoryTokenToUsers < ActiveRecord::Migration
def change
add_column :users, :type, :string
add_column :users, :memory_token, :string
end
end
which will make the changes after running rake db:migrate
Related
I'm trying to add new column into the table by 'rake db:migrate',but it return nothing in cmd.Then i try 'rake db:migrate:status' this time it return the following...
C:\Sites\seas>rake db:migrate:status
database: seas_development
Status Migration ID Migration Name
--------------------------------------------------
up 20160323084854 Create equipment
up 20160329072332 Devise create users
Below is inside my migration file...
class CreateEquipment < ActiveRecord::Migration
def change
create_table :equipment do |t|
t.string :name
t.string :equip_id
t.date :buy_date
t.string :brand
t.string :note
t.date :exp
t.string :status
t.string :serial
t.float :price
t.string :pic_id
t.string :ownby
t.timestamps null: false
end
add_column :equipment, :process ,:string
end
end
This only happen if there exist some data in the table,otherwise migration work fine.
Any suggestion ?
You have a typo
add_column :equipment, :process ,:string
Table name should be in plural
add_column :equipments, :process ,:string
But... if the migration had already be ran, then it will not run again. Create a new migration
rails g migration add_process_to_equipments process
rake db:migrate
Ta dah!
I have this table:
class CreateShoes < ActiveRecord::Migration
def change
create_table :shoes do |t|
t.string :name
t.boolean :leather
t.integer :season
t.timestamps null: false
end
end
end
the 'season' column should be called 'season_id'. I know that I have to write 't.rename :season, :season_id' as explained in http://edgeguides.rubyonrails.org/active_record_migrations.html#column-modifiers but I don't manage to find the right syntax. Should it be?
class CreateShoes < ActiveRecord::Migration
def change
create_table :shoes do |t|
t.string :name
t.boolean :leather
t.integer :season
t.timestamps null: false
end
change_table :products do |t|
t.rename :season, :season_id
end
end
end
Doesn't work. Anything I have to do in the Mac console? Thanks!
Run in your console:
$ rails g migration rename_season_to_season_id
Now file db/migrate/TIMESTAMP_rename_season_to_season_id.rb contains following:
class RenameSeasonToSeasonId < ActiveRecord::Migration
def change
end
end
Modify it as follows:
class RenameSeasonToSeasonId < ActiveRecord::Migration
def change
rename_column :shoes, :season, :season_id
end
end
Then run $ rake db:migrate in console.
Either fix your migration and do
rake db:rollback db:migrate
or make another migration like so:
rename_column :shoes, :season, :season_id if column_exists?(:shoes, :season) && !column_exists?(:shoes, :season_id)
and then do
rake db:migrate
If your intention is to rename column in table than you example migration is not making sense :)... Instead of this
class CreateShoes < ActiveRecord::Migration
def change
create_table :shoes do |t|
t.string :name
t.boolean :leather
t.integer :season
t.timestamps null: false
end
change_table :products do |t|
t.rename :season, :season_id
end
end
end
You just need table change migration, like this(Rails will take care rollback for your):
class RenameSessionColumnInsideShoes < ActiveRecord::Migration
def change
change_table :products do |t|
t.rename :season, :season_id
end
end
end
rename method on table object in rails is valid method, as you can see in Rails source code
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb#L582
If your branch has been pushed to production then one probably needs to add the new migration by running the following command:
rails g migration RenameSeasonColumnNameToShoes
and if it hasn't been pushed to production or you have to currently make changes to your branch only, then do:
bundle exec rake db:rollback
Then make changes to your migration file inside /db/migrate/<your_migration_file_name>
Then in your migration file, using rename_column do as follows:
class RenameSeasonColumnNameToShoes < ActiveRecord::Migration
def change
rename_column :shoes, :season, :season_id
end
end
and then do
bundle exec rake db:migrate db:test:prepare
I'm struggling here with the db migration for the acts_as_commentable_with_threading.
After generating the migration rails generate acts_as_commentable_with_threading_migration I proceeded to add the comment table rake db:migrate. Nothing happened, no error message, just returned to the regular prompt.
Looking at other response to this problem I tried rake db:migrate VERSION= # version number.
Yet here I get an Error response ActiveRecord::UnknownMigrationVersionError:
I must be doing something extremely wrong here since the computer doesn't validate the existence of my comment migration...
UPDATE from #Tiago answer
Ran rails generate migration acts_as_commentable_with_threading_migration
I had to manually create the migration by adding this code to the migration file. Then, thedb:migration worked perfectly.
Why wasn't it working in the first place? The Documentation clearly indicate to run rails generate acts_as_commentable_with_threading_migration.
Just create a migration for yourself as indicated in the gem's page:
rails g migration acts_as_commentable_with_threading_migration
And paste that to the file:
class ActsAsCommentableWithThreadingMigration < ActiveRecord::Migration
def self.up
create_table :comments, :force => true do |t|
t.integer :commentable_id, :default => 0
t.string :commentable_type
t.string :title
t.text :body
t.string :subject
t.integer :user_id, :default => 0, :null => false
t.integer :parent_id, :lft, :rgt
t.timestamps
end
add_index :comments, :user_id
add_index :comments, [:commentable_id, :commentable_type]
end
def self.down
drop_table :comments
end
end
I am trying to create a user_roles table in my engine that joins the user with a particular role allowing that user to have one or more roles.
I have the following migrations:
User
-- This migration works fine.
class CreateXaaronUsers < ActiveRecord::Migration
def change
create_table :xaaron_users do |t|
t.string :first_name
t.string :last_name
t.string :user_name
t.string :email
t.string :password
t.string :salt
t.timestamps
end
end
end
Roles
-- This migration works fine
class Roles < ActiveRecord::Migration
def change
create_table :xaaron_roles do |t|
t.string :role
t.timestamps
end
end
end
user_roles
-- This migration explodes stating that column user_id doesn't exist. I assume that this migration, dealing with indexes and the such, would create the appropriate columns referencing what I am telling it to reference.
class UserRolesJoin < ActiveRecord::Migration
def change
create_table :xaaron_user_roles, id: false do |t|
t.references :xaaron_user, null: false
t.references :xaaron_role, null: false
end
add_index :xaaron_user_roles, :user_id
add_index :xaaron_user_roles, [:role_id, :user_id], unique: true
add_index :xarron_roles, :role, unique: true
end
end
The exact error is:
PG::UndefinedColumn: ERROR: column "user_id" does not exist
: CREATE INDEX "index_xaaron_user_roles_on_user_id" ON "xaaron_user_roles" ("user_id")/Users/Adam/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:in `async_exec'
/Users/Adam/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:in `block in execute''
Did I fail at typing something? Why is this migration failing, aside from the obvious?
If you just want to create a join table then,
1. Remove the existing migration
rails d migration UserRolesJoin
2. Create a new migration for join table as
rails g migration CreateJoinTableUserRole user role
This will create a migration like:
class CreateJoinTableUserRole < ActiveRecord::Migration
def change
create_join_table :users, :roles do |t|
# t.index [:user_id, :role_id]
# t.index [:role_id, :user_id]
end
end
end
NOTE: You need to uncomment one of the combination as per your requirement from the generated migration.
3. Run rake db:migrate
I created a users table via "rails generate model User name:string email:string ..." the migration file was created as well.
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.timestamps
end
end
end
Now I want to add an index to the email column "following the tutorial" I've done this successfully the first time through using sqlite3. Second time through im using MySql (mysql2). Again created the table fine with generate model.. When I run the following:
rails generate migration add_index_to_users_email
the process ends with no error message and creates the migration file as shown below, but there is no setting of any index..
class AddIndexToUsersEmail < ActiveRecord::Migration
def change
end
end
Im expecting to see add_index :users, :email, unique: true in there ... Anybody have any idea's.. searched other threads to no avail.. running rails 4, mysql 5.6 ruby 1.9.3 my schema that was created after initil db:migrate is:
ActiveRecord::Schema.define(version: 20131024161033) do
create_table "users", force: true do |t|
t.string "name"
t.string "email"
t.string "city"
t.string "state"
t.string "zip"
t.string "mobile_phone"
t.string "mobile_phone_type"
t.date "birth_date"
t.string "user_type"
t.string "ss_num"
t.boolean "agree_to_terms"
t.datetime "created_at"
t.datetime "updated_at"
end
end
via http://guides.rubyonrails.org/migrations.html
If you'd like to add an index on the new column, you can do that as
well:
$ rails generate migration AddPartNumberToProducts
part_number:string:index
your generator
rails generate migration add_index_to_users_email
simply creates an empty migration file and did not describe a index
so this would be more appropriate...
rails generate migration AddIndexToUsers email:string:index
should give you
class AddIndexToUsers < ActiveRecord::Migration
def change
add_index :users, :email
end
end
Nguyen You - EDIT
This command [Rails 5.2.3]
rails generate migration AddIndexToUsers email:string:index
actually will give you
class AddIndexToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :email, :string
add_index :users, :email
end
end
not only add_index but also add_column to the users table.
rails generate migration AddIndexToUsers email:string:index
if you already have column it just add index, like:
class AddIndexToUsers < ActiveRecord::Migration
def change
add_index :users, :email
end
end
if you create new column (you haven't got column in database yet), it returns:
class AddIndexToUsers < ActiveRecord::Migration
def change
add_column :user, :email, :string
add_index :users, :email
end
end
From the http://railstutorial.ru/chapters/4_0/modeling-users#code-email_uniqueness_index.
The email uniqueness migration is not pre-defined, so we need to fill in its contents with this by ourself " add_index :users, :email, unique: true " .
The result will be:
class AddIndexToUsersEmail < ActiveRecord::Migration
def change
add_index :users, :email, unique: true
end
end