Learning Rails 3.0 - Migration Help - belongsTo
I'm working on a photo gallery app. Photo has a belongsTo relationship to Album (Album has_many realtionship to Photo) How do I create the migration that adds this relationship to the database correctly? I have tried - rails generate add_album_to_photo but that comes th开发者_如何学JAVArough as an empty migration. I could use a push in the right direction.
Assuming tables albums
and photos
exist already, all you have to do is add a column album_id
to your photos
table:
class AddAlbumToPhoto < ActiveRecord::Migration
def self.up
add_column :photos, :album_id, :integer
end
def self.down
remove_column :photos, :album_id
end
end
Or:
class AddAlbumToPhoto < ActiveRecord::Migration
def self.up
change_table :photos do |t|
t.references :album
end
end
def self.down
change_table :photos do |t|
t.remove :album_id
end
end
end
Or if you insist on generating the code:
rails g migration add_album_to_photo album_id:integer
精彩评论