How do I create a new field in an existing table using the Ruby command prompt?
I created the model (and migrated it) but I forgot to add a field - how would I go about this?
Generate a new migration to add a new column to table.
rails g migration add_column_name_to_table_name column_name:type
This will create a migration class like below:
#config/migration/20150304121554_add_column_name_to_table_name.rb
class AddColumnNameToTableName < ActiveRecord::Migration
def change
add_column :table_name, :column_name, :type
end
end
Here, column_name, table_name and type should be your desired name and type. Than run rake db:migrate command.
There are two ways to make changes in your situation:
Roll back the last migration
Add the new field in a new migration
Undoing the last migration should only be done if you have not yet pushed the migration to a public server. Here's how to do it:
Run rake db:rollback
Add the new field to the same migration file you originally used
Run rake db:migrate
Option 2:
To add the field in a new migration:
rails g migration AddFieldNameToTableName
For example, if your field is name and your table is users, you would run:
rails g migration AddNameToUsers
This will create a new migration file whose name starts with today's date and ends with add_name_to_users.rb. Open the file and add the field using the add_column command, like this:
class AddNameToUsers < ActiveRecord::Migration
def change
add_column :users, :name, :string
end
end
Save the file, then run rake db:migrate.
I encourage you to read the Rails migrations guide to learn more.
Related
I have created 2 tables (categories and products) and I did has_many association like Category has_many :products and Product belongs_to :category.
When I do a migration like:
rails generate migration add_product_id_to_categories product_id:integer
then migration is running but not seeing product_id in Category.
I've tried multiple ways like
add_product_id_to_category product_id:integer
but still facing the same problem.
You only generated a migration file (rails generate migration add_product_id_to_categories product_id:integer). You have to run the migration with rake db:migrate.
Generating a migration is a different thing than actually running it. You just generated it, and in order to execute what you have written, you need to run it, and you can do so by invoking the following command:
rake db:migrate
Not sure that either you have run the migration or not, run the following command, and it will tell you the statues of all the migrations. If the status is up, the migration has been run, and for down, a migration couldn't be run.
rake db:migrate:status
When you run a migration, and you would like to get notified in terminal that it has been successfully run, you can add a puts statement in there like following:
class AddColumnToCategories < ActiveRecord::Migration
def change
add_column :categories, :product_id, :integer, index: true
puts "product_id column has been added into categories."
end
end
Have you tried rails generate migration AddProductIdToCategories product_id:integer?
When you have created the migration if you look inside the migration file you can see if any code has been generated in the change method before you run the migration. If it has not generated any content you can manually add it:
def change
add_column :categories, :product_id, :integer
end
I tried to create a migration to add roles to my user tables but i accidentally typed AddRolesToUsers instead of AddRoleToUser. So i tried creating a new migration with the correct AddRoleToUsers but when i tried to run rake db:migrate i got an error :
SQLite3::SQLException: duplicate column name: role: ALTER TABLE "users" ADD "role" integer/Users/miguel/.rvm/gems/ruby-2.2.1/gems/sqlite3-1.3.11/lib/sqlite3/database.rb:91:in `initialize'
I tried rake db:migrate:down VERSION= do delete the one I had to type on but i keep getting the same error . PS: i deleted the migration file manually after running rake db:migrate:down VERSION=
rails g migration AddRoleToUsers role:integer
migration file :
class AddRoleToUsers < ActiveRecord::Migration
def change
add_column :users, :role, :integer
end
end
When you ran the first migration, the role column was added to the Users table. The error on the second migration tells you that much.
To clear the migration pending error, you need to comment out the add_column statement in the new migration.
i.e,
class AddRoleToUsers < ActiveRecord::Migration
def change
# add_column :users, :role, :integer
end
end
Then run the migration. This way, the new migration should run successfully.
You can now uncomment it and delete the previous migration, so that when you deploy, only the newer migration is run and the role column is added successfully.
In that case right click and delete both migration files and start again. The error exists because it thinks you want to add two columns both named role to your users table
UPDATE
In that case, if role already exists in your users table, a migration must've been successfully run and there is no need to run another. As long as the role column is there, trying to add another column called role will always give you an error. If you wanted to test that you are still able to add new columns you can always check by creating a test migration AddSomethingToUsers something:string and rake db:migrate to test, then rake db:rollback to undo..but it all seems like it's worked so I probably my wouldn't mess with it too much.
I'm very new to ruby on rails, been trying to play around with it in the past few days.
Basically trying to: Create a empty table, with fixed columns - Ruby on Rails
I've created a model like so:
rails g model table
rails g migration table
my tables.rb files looks like this:
class Tables < ActiveRecord::Migration
def change
add_column :table, :firstname, :string
add_column :table, :lastname, :string
end
end
(hopefully I created the columns okay)
I then run:
rake db:migrate RAILS_ENV=development
but seem to get an error no such table: table (but I thought I created it ? )
Also what is a good view I can use to see my table on localhost:3000, in a html.erb file?
What you are displaying as your tables.rb file is a migration file, not a model. Models are stored in app/models. Migrations are in db/migrate and have a name that is a datetime stamp followed by the migration name.
Your migration is performing add_column. You can't add_column until you create_table. That migration should have been built using "rails g model table". Please show all migrations with the entire filename.
Check the document that dax provided. The rails generate command uses a stylized command line. Many standard migration functions, such as creating tables and adding columns, can be automatically generated by using the correct migration name. For example:
rails g migration add_url_to_feed url:string
This will create a migration that adds a string column called url to the feed table.
Generally, migrations should do what you need. However there is another command, rake, that you will need. The reference is here. For example:
rake db:create # Create the database from config/database.yml for the current Rails.env
can create the database for you.
I have migration (created way back) that i need to change, it's the below:
20130923000732_create_questions.rb
I need to change
t.string to --> t.text
how can i achieve this ?
I read along that i can create a new migration renaming the column, but i did not quite understand it.
If 20130923000732_create_questions.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=20130923000732
After rollback your migration, change your migration file and migrate again.
Your app is in development yet, just open that migration in edtor, change it to text and run all your migrations again.
Or write a migration that will update that field type.
First in you terminal:
rails g migration change_column_type_in_questions
Then in your migration file:
class ChangeColumnTypeInQuestions < ActiveRecord::Migration
def change
change_column :questions, :body, :text
end
end
Migration will look for table questions and will update column body type without loosing data.
Run rails generate migration change_string_to_text_in_questions then a new migration file will be created, with
def change
end
method, now insert, change_column :table_name, :column_name, :type now your migration file should look like this,
def change
change_column :table_name, :column_name,:type
end
After this, Save the Changes and run db:migrate
All,
I need clarification on how model changes need to tracked in ruby on rails. I started off by creating a model with say two fields, name and email. Here is what i have done
Created a model by running
"rails generate model user first_name:string last_name:string"
This created a model file
I then added some validations to the files created in user
Used the annotation gem to annotate the class
used "bundle exec rake db:migrate" to move my model to database which created the tables
I now want to add a couple more fields to the model. What steps do i need to follow?
Do i add columns to the database and run some command so that the model(class) is in sync with the db?
Do i delete and recreate the whole model with the new fields?
what is the recommended approach
Venu
You want to use a migration to update the existing table, you can do the entire process from the command line
Assuming you've done
rails generate model user first_name:string last_name:string
previously you would add fields like so;
rails generate migration AddFieldsToModel new_field:string another_field:string....
Rails does magic on the 'AddFieldsToModel' and works out the table name from the value for you.
Once you've created the migration you can look at it in db/migrations and then if you're happy with it just run
rake db:migrate
this will update your database to add the new fields to it. You don't need to do anything to the actual model.rb file - but you will need to re run the annotate task to have it reannotated to the model.rb file.
I am not sure what version of rails your are using .. but int rails 3.x it can be done as
rails generate migration add_fields_user
this creates a file in db/migrate/[timestamp]/add_fields_user.rb
now you can write in the file and run rake db:migrate
add_column :users , :city, :string
What you want to do is run a migration by typing. rails generate migration description_of_migration. This will create an empty migration which you can define what you want to add to your model. In your case it may be something like this:
class DescriptionOfMigration < ActiveRecord::Migration
self.up
add_column :users, :email, :string
end
self.down
remove_column :users, :email
end
end
This makes it so you can migrate both ways on the model.