Adding data to model vs migration

On page 198 Patrick generates a Vote model by:

ruby script/generate model Vote story_id:integer

and then changes the vote/story class so that they read:

class Vote < ActiveRecord::Base
belongs_to :story
end

class Story < ActiveRecord::Base
has_many :votes
end

Would an equivalent database schema be derived by not adding the story_id:integer as so:

ruby script/generate model Vote

and then change the vote/story class so that they read:

class Vote < ActiveRecord::Base
belongs_to :story
end

class Story < ActiveRecord::Base
has_many :votes
end

and changing the create_stories.rb migration to read thus:

class CreateStories < ActiveRecord::Migration
def self.up
create_table :stories do |t|
t.string :name
t.string :link

  t.timestamps
end
add_column :votes, :story_id, :integer

end

def self.down
drop_table :stories
remove_column :votes, :story_id
end
end

##################################################

It seems to me that this gets the story_id column in the votes table, but allows for it to be removed again through a migration. The hard coded addition to the model seems to preclude the schema from ever being changed.

Is there a distinction, or was this done for pedagogical reasons?

Thanks,

John

I need to make complex changes to my database, such as moving columns to another table, while at same time preserving my existing data, With Data Studio Administrator for DB2® for Linux®, UNIX®, and Windows® formerly known as DB2 Change Management Expert can i change it?then how?plz help me.

The original works best if the votes table doesn’t already exit. Your technique works best if it does exit.

In general, I would suggest that you try create each table with its own migration. That’s easier to read and what people expect so will be easier to maintain. Then add migrations when you need to change your original design. It can make sense to make all the changes that relate to a particular change within a single migration and in this case it can make sense to update more than one table at a time.

For example if some way along the development path, you decide to start using foreign keys via the foreigner plug-in. It would make sense that you add the keys to all the tables within a single migration.