I am working on a Rails application where the previous developer had created a Users model, then later dropped it in lieu of another solution. The migration files are still in the repository, but obviously the table doesn't exist. I am now trying to create a User authentication system to integrate a blog, but I am running into the issue of the previous migration and getting the following error message when trying rails g model User:
"Another migration is already named create_users..."
Is it possible there a way to create Users again?
Just to be extra clear. There is a create_users and later a drop_users migration.
1. $ rails g model User --migration=false
2. $ rails g migration create_users_again
3. open create_users_again migration file (created in step 2), and define your table as:
def change
create_table :users do |t|
t.email :string
t.timestamps
end
add_index :email
end
You can look your old create_users migration file for help.
When the previous developer ran rails g model user, this created a migration class like so:
class CreateUsers < ActiveRecord::Migration
Now that you are running rails g model user, Rails is complaining that that class CreateUsers, already exits.
You can either:
Rename the previous migration to CreateUsersPrevious (don't forget to rename the migration file as well xxxxxxxxxxx_create_users_previous.rb) if you would like to keep it documented in your migration history
Remove the old migration file
Related
rails g migration MigrationName
rails g model MigrationName
I know these two commands. I am confused when to use which command as function of both look similar.
Also how those files created by them are different.
If you run rails g model ModelName then you'll get a result similar to the following:
rails g model User
invoke active_record
create db/migrate/20200430143738_create_users.rb
create app/models/user.rb
invoke test_unit
create test/models/user_test.rb
create test/fixtures/users.yml
As you see, it creates a model file (in this case User), the migration file automatically named as create_yourmodelname_plural, plus a test file and a fixture for the model.
On the other hand, if you run rails g migration MigrationName, you are just creating a migration file. So, if you were to create a user table, you'll get a similar result:
rails g migration CreateUsers
invoke active_record
create db/migrate/20200430144301_create_users.rb
In conclusion, the first case can be used when you do not have a model nor the corresponding table in the database: you can easily create both a model file and a migration file with this automatically prefilled content (in this example the model is User):
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
end
end
end
The second case is used instead for specifically creating just a migration file - for any purpose (updating or even deleting a table, for instance), not only the creation of a new table.
I hope this can help :)
Well the main difference is that the second one should be rails g model ModelName doesn't just create a migration, but also creates a model file and a spec file for that model. It also will most generate a create table migration, whereas with rails g migration MigrationName, you can just do very specific migrations such as adding an index, or adding/removing columns. Sections 2.1 and 2.2 will help you get a better grasp: http://guides.rubyonrails.org/migrations.html
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 already read the documentation of "migrate" on Rails 3 (Rails 3.0 Relese Notes Migrate) but I have some doubts.
e.g. I created two class:
rails generate scaffold User name:string age:integer height:float
rails generate scaffold Hat type:string width:float height:float
This create models, controllers, ... User and Hat and its migrate class: xxx_create_users.rb and xxx_create_hats.rb
Ok, now we guess we want modify User class and we delete height attribute, and we add the relationships between Users and Hats:
User
class User < ActiveRecord::Base
attr_accessible :name, :age
has_many :hats
end
Hat
class Hat < ActiveRecord::Base
attr_accessible :type, :width, height
belongs_to :user
end
Options that I guess:
I remove all files xxx_create_xxx.rb and then I will create again with: rails generate migration CreateUser (and the same for Hat)
I create a new migration file: rails generate migration MyNewMigration where I codify by hand all changes.
Is there another way to automate changes in my classes for passed it to the database? What is the correct way to proceed?
The idea of migrations is that you have a stringent storyline where you can start at any point, forward and backwards. This means that it should not ever be necessary to delete a migration.
Instead, you create a new migration that will change, remove or add database fields.
In your example, you would leave the old migration where it is and then create a new migration like so:
rails g migration change_user_fields
And inside def up you write
remove_column :table_name, :column_name
change_column :table_name, :column_name, :data_type
Add a def down - this will be run whenever the migration is reversed by rake db:rollback. Inside def down put:
add_column :table_name, :column_name # add the field that you removed (s.a.)
change_column :table_name, :column_name, :data_type # change back to old data type
Rails 3 gives you a nice shortcut for adding and removing fields from a table by doing:
rails g migration add_something_to_users name:string
which will automatically create a migration that adds a field called name with a data type of string to the users table. Or
rails g migration remove_something_from_users name
which will automatically create a migration to remove the name field from the users table. These shortcuts and the created migration files do not need a def down - rails will automatically be smart enough to figure that out when reversed.
In both cases, you can replace the word "something" with whatever you like.
However, I know of no way to use a shortcut to change data types, so you need to go in the migration file and do that manually.
Eventually, just run rake db:migrate and you'll be all set!
Scaffold only automate a fixed command, so if you create a model and its attributes with scaffold, your migration will only contain the fields you specify on the command line. There is no way to keep track of changes automatically.
If you add/remove/change something on your database, you have to manually set it. Migrations are useful because you can keep track of these changes on time.
So i recommend you to never delete a migration. In this particular case you described, you just have to create another one to reflect the new change on your database, keeping a total of 3 migrations, instead of deleting and creating another.
The answer to your question should be alternative 2. But you don't have to do it all by hand if you just want to add or remove attributes:
http://guides.rubyonrails.org/migrations.html#creating-a-standalone-migration
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.
I was wondering if anyone knew how to update the files (adding/removing/updating an attribute) produced by using the scaffold generator in ruby on rails.
For example:
scaffold student name:string lastname:string
so this will create a the associate files (controller,view,etc) with name and lastname as string attributes. When you db:migrate the project, it'll create the table in the database. However, say I want to update whether it be update it with an addition attribue (ex. studenId:integer) or if its removing or updating an attribute, how do you do that?
I tired just updating the generated files, but when I do that db:migrate it still sets the schema that is generated to what is in the table. Is there a built in script in rails that will update the table?
Any advise appreciated?
Thanks,
D
Full command in this example:
$ rails generate migration add_studentid_to_student
You need new migration file for new attributes, from console:
$ script/gnerate migration add_sudentid_to_sudent
it will generate your_app/db/migrate/8293898391_add_sudentid_to_sudent.rb, spicify in this file your new attributes:
def self.up
add_column :sudents, :studentId, :integer
end
def self.down
remove_column :students, :studentsId
end
after that, back to console:
$ rake db:migrate
and than you can edit your views, model, controller files and use new attribute
Hi Try ruby script/destroy scaffold student and then ruby script/generate scaffold student
also try reading up on rails migrations, for dropping/updating table columns.
http://api.rubyonrails.org/classes/ActiveRecord/Migration.html