If I change the database in a live Ruby on Rails app, how do I update the data?
So I'm finally ready to allow some friends to use my Ruby on Rails app, 开发者_运维百科which I'm hosting on Heroku. I want to start getting some feedback as I'm still developing.
What happens if I need alter to the database in some way? There will be data in the database, so I will have to change the data to reflect the updates in the database, but I'm not sure how this is done. Thanks for reading.
Normally the best practice is to create a production database for real users. (Even though your is app still in beta stages). Having a separate production and development database will make your life lot easier.
Ex: development databases often have corrupted data, meaning less dummy data etc..
- When changing your data structure you can do followings
- always do your changes with a migration (Its easy to revert, rollback etc)
- when your are inserting values to a table, create a migration for that. (This will save you from uploading same data multiple times)
- When you write a migration, always make sure you have the proper rollback method (self.down)
- Always you default values
cheers
sameera
Did you use migrations to create your database? If so, then all you would have to do to change the database would be to create a migration that adds/drops/changes a table in the database. For example:
class AddMyColumnToMyTable < ActiveRecord::Migration
def self.up
add_column :table, :my_column, :string
end
def self.down
remove_column :table, :my_column
end
end
Then to add/remove data, you create a data migration like so:
class AddDataToMyTable < ActiveRecord::Migration
def self.up
tables = Table.all
tables.each do |table|
table.my_column = 'new value' # Put more meaningful data population here
table.save!
end
end
def self.down
tables = Table.all
tables.each do |table|
table.my_column = nil
table.save!
end
end
end
Data migrations can be as simple or as complicated as you want them to be. Data migrations are not necessarily the best way to populate your database in all cases, but for simple cases they work really well. (Don't forget to update any models with appropriate relationships!)
If you didn't create your database via migrations, then changing the data to reflect the updates to the database can only be accomplished through direct manipulation of the database via SQL. Manipulation via SQL is always an option in a Rails app, but migrations provide distinct advantages. They give you the ability to commit or rollback changes to the database structure, not just the data. And, migrations do the SQL work for you.
精彩评论