I am working through the book Rails Test Prescriptions and during the setup it is asking me to change a migration file to the following:
class ProjectUserJoin < ActiveRecord::Migration
def self.up
create_table :projects_users, :force => true, :id => false do |t|
t.references :project
t.references :user
t.timestamps
end
end
def self.down
drop_table :projects_users
end
end
It seems I am using a later version on Rails (4.0.0) than the book (2 or 3.x) and my migration file looks like this:
class ProjectUserJoin < ActiveRecord::Migration
def change
end
end
How do I edit the change method to do the same as the up and down methods above? So far I have tried using up and down as opposed to self.up and self.down and copying in the same code. It did not work.
Thanks!
The up method should describe the transformation you'd like to make to your schema, and the down method of your migration should revert the transformations done by the up method. In other words, the database schema should be unchanged if you do an up followed by a down.
It will run these migrations in order based on the date of the migration. Note that running the db:migrate also invokes the db:schema:dump task, which will update your db/schema. rb file to match the structure of your database.
To check for status, run rails db:migrate:status . Then you'll have a good view of the migrations you want to remove. Then, run rails db:rollback to revert the changes one by one. After doing so, you can check the status again to be fully confident.
Just change def change
with def self.up
content.
You can check the result by running rake db:migrate
at your console - it will create the table (self.up functionality) and rake db:rollback
- it will drop the table (self.down functionality).
Your up/down
migration would look like this for change
:
class ProjectUserJoin < ActiveRecord::Migration
def change
create_table :projects_users, :force => true, :id => false do |t|
t.references :project
t.references :user
t.timestamps
end
end
end
The change method is able to automatically figure out the down actions required based upon the create/update information you provide. It is not a complete replacement for the original self.up/self.down methods however as some database actions you take Rails is not able to automatically figure out what is the corresponding up/down actions. On example of this is if you need to run an arbitrary SQL statement execute-<<SQL ... SQL
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With