For example i have this model:
class Product < ActiveRecord::Base
attr_accessible :name, :order
end
Then when i did rake db:migrate
it created this db/migrate/20120825132038_create_products.rb:
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.integer :order
t.string :name
t.timestamps
end
end
end
But it all happend cuz i used rails generate Product order:integer name:string
Now after i go to Product model and changes it manually to:
class Product < ActiveRecord::Base
attr_accessible :name, :order, :category_id
validates :name, uniqueness: true
belongs_to :category
end
How can i auto update the db/migrate/20120825132038_create_products.rb with the updates?
You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.
down. The down command executes the migrations of your currently configured migrations directory. More specific the down migrations are being called. Down migrations are called in reverse order in which the up migrations previously were executed.
When you ran rake db:migrate
, it did not create db/migrate/20120825132038_create_products.rb
. That migration file was created when you ran
rails generate Product order:integer name:string
attr_accessible
has nothing to do with migrating your database.
I strongly recommend you read the Rails Guide on Migrations, as well as the section on Mass Assignment which discusses attr_accessible
.
To generate a new migration file (since the one mentioned in your Question has already been processed by the previous rake db:migrate
command you mentioned running), run
rails g migration AddCategoryIdToProduct category_id:integer
This should generate a new migration with contents like
class AddCategoryIdToProduct < ActiveRecord::Migration
def change
add_column :products, :category_id, :integer
end
end
Running rake db:migrate
again now will process this migration file, adding the new category_id
integer column to your products
table.
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