开发者

How do I add a new attribute to a migration in Rails 3?

开发者 https://www.devze.com 2023-03-31 03:46 出处:网络
Here\'s my story: I had something like this set up a while ago. create_table(:users) do |t| t.database_authenticatable :null => false

Here's my story: I had something like this set up a while ago.

  create_table(:users) do |t|
  t.database_authenticatable :null => false
  t.r开发者_开发知识库ecoverable
  t.rememberable
  t.trackable

  t.integer :total_pageviews

and "total_pageviews" worked fine. I could set it to zero, increment it, multiply it, call it, whatever. but let's say i want to add:

  t.integer :total_votes

What do I have to do to configure total_votes as an attribute? Whenever I try to use "total_votes", I get undefined method error. I'm thinking that the answer is something like rake db:migrate or similar.


You should not ever alter existing migrations. If you have checked them in to your version control system and somebody else runs them and then you add a new field to them and commit that change, they will not know to get that change. Then you must tell them and it's a pain in the butt to fix.

If you've not committed it yet then rollback the migration (rake db:rollback), make the necessary modification and re-run it again (rake db:migrate).

But in the Real World, you would create a new migration which adds this field using rails g migration add_total_votes_to_users total_votes:integer.

Rails will interpret this migration name and know what to do with it, generating a migration that contains this line:

add_column :users, :total_votes, :integer

Then when you run this migration it will add this total_votes field to the users table which will make an attribute of the same name for all User objects.


Are you adding this after the migration has been run? So, the users table exists and you want to add a column to it? If so, you need go create a migration like

rails generate migration add_total_votes_to_users 

Open it up (just to verify that the table and column are correct). Then run the migration.


If you app is in production, then you should create a new migration. If you app is in pre-production stage, and you have a small development team with good communication, then I recommend you to go ahead and modify the migration and then do

rake db:drop
rake db:create
rake db:migrate

then you can commit the modified migration file and let the rest of you team know that that you have changed a migration file.

0

精彩评论

暂无评论...
验证码 换一张
取 消